日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python遍历txt每一行_python – 计算(和写入)文本文件中每一行的...

發布時間:2023/12/13 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python遍历txt每一行_python – 计算(和写入)文本文件中每一行的... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

第一次在堆棧中發布 – 總是發現以前的問題足以解決我的問題!我遇到的主要問題是邏輯……即使是偽代碼答案也會很棒.

我正在使用python從文本文件的每一行讀取數據,格式如下:

This is a tweet captured from the twitter api #hashtag http://url.com/site

使用nltk,我可以逐行標記,然后可以使用reader.sents()迭代等:

reader = TaggedCorpusReader(filecorpus, r'.*\.txt', sent_tokenizer=Line_Tokenizer())

reader.sents()[:10]

但我想計算每行某些“熱詞”(存儲在數組或類似詞中)的頻率,然后將它們寫回文本文件.如果我使用reader.words(),我可以計算整個文本中“熱詞”的頻率,但我正在尋找每行的數量(或者在這種情況下為“句子”).

理想情況下,例如:

hotwords = (['tweet'], ['twitter'])

for each line

tokenize into words.

for each word in line

if word is equal to hotword[1], hotword1 count ++

if word is equal to hotword[2], hotword2 count ++

at end of line, for each hotword[index]

filewrite count,

另外,不要擔心URL被破壞(使用WordPunctTokenizer會刪除標點符號 – 這不是問題)

任何有用的指針(包括偽或其他類似代碼的鏈接)都會很棒.

—-編輯——————

結束這樣的事情:

import nltk

from nltk.corpus.reader import TaggedCorpusReader

from nltk.tokenize import LineTokenizer

#from nltk.tokenize import WordPunctTokenizer

from collections import defaultdict

# Create reader and generate corpus from all txt files in dir.

filecorpus = 'Twitter/FINAL_RESULTS/tweetcorpus'

filereader = TaggedCorpusReader(filecorpus, r'.*\.csv', sent_tokenizer=LineTokenizer())

print "Reader accessible."

print filereader.fileids()

#define hotwords

hotwords = ('cool','foo','bar')

tweetdict = []

for line in filereader.sents():

wordcounts = defaultdict(int)

for word in line:

if word in hotwords:

wordcounts[word] += 1

tweetdict.append(wordcounts)

輸出是:

print tweetdict

[defaultdict(, {}),

defaultdict(, {'foo': 2, 'bar': 1, 'cool': 2}),

defaultdict(, {'cool': 1})]

總結

以上是生活随笔為你收集整理的python遍历txt每一行_python – 计算(和写入)文本文件中每一行的...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。