Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python从计数器向文件获取信息_Python_File_Counter - Fatal编程技术网

Python从计数器向文件获取信息

Python从计数器向文件获取信息,python,file,counter,Python,File,Counter,我有一个满是句子的文件,我想用它做一个单字: 这是我的密码,只有一个字母,我想让它得到这个单词 old_lines = open("f.final",'r').readlines() new_lines = [] for line in old_lines: words = line.split() new_lines.append(words) print new_lines for lines in new_lines: c = Counter(str(lin

我有一个满是句子的文件,我想用它做一个单字:

这是我的密码,只有一个字母,我想让它得到这个单词

old_lines = open("f.final",'r').readlines() 
new_lines = []

for line in old_lines:
    words = line.split()
    new_lines.append(words)

print new_lines

for lines in new_lines:
    c = Counter(str(lines))


with open("final.final", 'w') as f:
    for k,v in  c.items():
        f.write("{} {}\n".format(k,v))

您正在从字符串(即strlines)构建计数器,strlines接受字符串中每个字符的计数。您应该直接从列表中构建计数器。所有行都应该这样做,而不仅仅是最后一行:

with open("f.final") as f, open("final.final", 'w') as out_f:
    # take count of all words from all lines
    c = Counter(word for line in f for word in line.strip().split())

    # write to output file
    for k, v in  c.items():
        out_f.write("{} {}\n".format(k,v))

在这一行中:c=Counterstrlines您一直覆盖计数器-这将只剩下最后一行…如果我想做二元、三元等等?@user8865346,那么您将使用nltk。您显示的代码仅尝试使用Unigram,因此我的答案仅针对.code old_lines=openf.final,'r'。readlines new_lines=[]lines=旧_lines中的行:lines=lines+line print lines token=nltk.word_tokenizelines bigrams=ngramstoken,2个打印计数器bigrams f=openf2.final,“在这里写什么?”代码我有这个问题,但我也有同样的问题,我不能把它从柜台放到文件里。它正确地打印出了二元图,但我不知道该怎么做do@user8865346你应该考虑把这个作为A。