【发布时间】:2016-05-24 21:07:02
【问题描述】:
从 file_test.txt 我需要使用 nltk.FreqDist() 函数计算每个单词在文件中出现的次数。当我计算词频时,我需要查看该词是否在 pos_dict.txt 中,如果是,则将词频数乘以 pos_dict.txt 中相同单词的数字。
file_test.txt 看起来像这样:
abandon, abandon, calm, clear
pos_dict.txt 在这些词中看起来像这样:
"abandon":2,"calm":2,"clear":1,...
我的代码是:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import nltk
f_input_pos=open('file_test.txt','r').read()
def features_pos(dat):
tokens = nltk.word_tokenize(dat)
fdist=nltk.FreqDist(tokens)
f_pos_dict=open('pos_dict.txt','r').read()
f=f_pos_dict.split(',')
for part in f:
b=part.split(':')
c=b[-1] #to catch the number
T2 = eval(str(c).replace("'","")) # convert number from string to int
for word in fdist:
if word in f_pos_dict:
d=fdist[word]
print(word,'->',d*T2)
features_pos(f_input_pos)
所以我的输出需要是这样的:
abandon->4
calm->2
clear->1
但是我的输出复制了所有输出并且显然乘法错误。我有点卡住了,我不知道错误在哪里,可能我使用的 for 循环错误。如果有人可以提供帮助,我将不胜感激:)
【问题讨论】:
-
您的输入文件是什么样的?你能发布一个链接或
file_test.txt和pos_dict.txt的示例吗? -
我的输入文件
file_test.txt看起来和我在问题中写的一样,在pos_dict.txt中包含其他词,但对于理解并不重要。
标签: python-3.x nltk