Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.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_Count - Fatal编程技术网

用Python计算文件中的字数

用Python计算文件中的字数,python,count,Python,Count,我对Python完全陌生,但令我自己惊讶的是,我编写了这段工作代码: if __name__ == "__main__": with open("wordlist.txt") as infile: for line in infile: print(line) with open ("cv000_29416.txt", "r") as myfile: data=myfile.read().replace('\n', '') print (data.co

我对Python完全陌生,但令我自己惊讶的是,我编写了这段工作代码:

if __name__ == "__main__":
with open("wordlist.txt") as infile:
    for line in infile:
        print(line)    



with open ("cv000_29416.txt", "r") as myfile:
   data=myfile.read().replace('\n', '')
print (data.count("bad"))      
重点是,我想计算cv000_29416.txt中wordlist.txt中的单词数

(例如,wordlist.txt包含20个单词,如“坏”、“好”等,而cv000_29416.txt是一个长文本,我想计算一下“坏”、“好”等在cv000_29416.txt中出现的次数)

我能把它插入到代码的某个地方吗

谢谢大家!! 抱歉英语不好

用听写器数一数所有单词:

from collections import Counter
with open ("cv000_29416.txt", "r") as myfile:
   data = Counter(myfile.read().split())
print (data["bad"])   
要将其放在一起,假设每个单词都位于wordlist.txt中的单独一行:

from collections import Counter
with open ("cv000_29416.txt", "r") as myfile,open("wordlist.txt") as infile:
    data = Counter(myfile.read().split())
    for line in infile:
        print(data.get(line.rstrip(),0))
用听写器数一数所有单词:

from collections import Counter
with open ("cv000_29416.txt", "r") as myfile:
   data = Counter(myfile.read().split())
print (data["bad"])   
要将其放在一起,假设每个单词都位于wordlist.txt中的单独一行:

from collections import Counter
with open ("cv000_29416.txt", "r") as myfile,open("wordlist.txt") as infile:
    data = Counter(myfile.read().split())
    for line in infile:
        print(data.get(line.rstrip(),0))

这可能会因为跟踪不需要的单词而浪费空间。理想情况下,只计算单词列表中的单词。txt@inspectorG4dget,它必须是一个相当大的文件才能产生任何影响,计数器dict正是OP应该学习的东西,而不是使用类似于
print(data.count(“bad”)
的东西。当然,
data.count(“bad”)
是坏的(没有双关语的意思)。但是,OP可以维护一个只包含所需单词的dict,并根据需要手动增加计数。这将节省空间,并且具有更大的可扩展性(对于大型/稀疏文件)另外,由于
collections
是用python编写的,所以它不会比手工编写的python快很多code@inspectorG4dget是的,OP可以做到这一点,但我猜OP可能想做的不仅仅是数一数这些单词。无论哪种方式,我都更愿意了解反指令,而不是notOP声明他们对cou感兴趣只从
wordlist.txt
中查找单词这可能会因为跟踪不需要的单词而浪费空间。理想情况下,只计算单词列表中的单词。txt@inspectorG4dget,它必须是一个相当大的文件才能产生任何影响,相反,反口述正是OP应该学习的东西要使用类似于
print(data.count(“bad”)
的东西,授予,
data.count(“bad”)
是不好的(没有双关语)。但是,OP可以维护一个只包含所需单词的dict,并根据需要手动增加计数。这将节省空间,并且具有更大的可扩展性(对于大型/稀疏文件)另外,由于
collections
是用python编写的,所以它不会比手工编写的python快很多code@inspectorG4dget是的,OP可以做到这一点,但我猜OP可能想做的不仅仅是数一数这些单词。无论哪种方式,我都更愿意了解反指令,而不是notOP声明他们对cou感兴趣NTIN只从“代码>单词列表。TXT < /代码>谢谢,这正是我正在寻找的!”HeleEnfijeNe:请考虑标记一个已接受的答案,以表示问题已经结束了,谢谢,这正是我正在寻找的!@ HeleEnffijeNe:请考虑标记一个已接受的答案,以表明问题是关闭的。