![](/img/trans.png)
[英]Count the number of words in a string by using a dictionary using a csv file in Python
[英]count occurrence of a words in a csv file in python using nltk
我試圖計算.csv文件中單詞“the”的出現次數,但是當我運行以下代碼時,它返回0.(test.csv位於此處 )
我只是搜索這個文件的第一列。
import csv
import nltk
tweet = []
for t in csv.DictReader(open('test.csv'), delimiter=','):
tweet.append(t['text'])
tweet_text = nltk.Text(tweet)
print tweet_text.count("the")
在此先感謝您的幫助。
使用str.split
text
字段拆分為單詞,並相應地使用list.extend
。 除非你只想要小寫the
否則制作小寫。
>>> nltk.Text(['the world The words']).count('the')
0
>>> nltk.Text(['the', 'world', 'The', 'words']).count('the')
1
完整代碼:
import csv
import nltk
tweet = []
for t in csv.DictReader(open('test.csv'), delimiter=','):
tweet.extend(t['text'].lower().split()) # <-----------
tweet_text = nltk.Text(tweet)
print tweet_text.count('the')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.