Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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 2.7 文本文件中的Python单词搜索_Python 2.7 - Fatal编程技术网

Python 2.7 文本文件中的Python单词搜索

Python 2.7 文本文件中的Python单词搜索,python-2.7,Python 2.7,我有一个文本文件,我需要在其中使用Python搜索特定的3个单词。例如,单词是account、online和offer,我需要计算它在系统中出现的次数 with open('fixtures/file1.csv') as f: print len(filter( lambda line: "account" in line or "online" in line or "offer" in line, f.readlines() )) 您还可以直

我有一个文本文件,我需要在其中使用Python搜索特定的3个单词。例如,单词是account、online和offer,我需要计算它在系统中出现的次数

with open('fixtures/file1.csv') as f:
    print len(filter(
        lambda line: "account" in line or "online" in line or "offer" in line,
        f.readlines()
    ))
您还可以直接检查单词是否在每行中

更新

要计算每个单词在一个文件中出现的次数,我发现最有效的方法是在该文件上迭代一次,并检查在该行中每个单词出现的次数。为此,请尝试以下方法:

keys = ('account', 'online', 'offer')

with open('fixtures/file1.csv') as f:
    found = dict((k, 0) for k in keys)

    for line in f.readlines():
        for k in keys:
            found[k] += 1 if k in line else 0
found
将成为一本包含您所查找内容的词典


希望这有帮助

我假设它是一个纯文本文档。在这种情况下,您将
以f
的形式打开('file.txt'),然后获取f中的每一行
[for],并检查
是否为f.lower()中的'word'
,然后相应地增加一个计数器(例如
wordxtotal+=1

您可以读取文本文件的内容,然后使用正则表达式来计算您希望出现的单词的次数上述代码正在工作,但它结合了3个单词的计数。我要数一数每一个字