【问题标题】:How to loop through and find a specific word in multiple text files?如何遍历并在多个文本文件中查找特定单词?
【发布时间】:2021-02-01 16:55:49
【问题描述】:

所以我编译了一堆 txt 文件,我让 python 将它们组合并在控制台中打印所有它们,如下所示:

import matplotlib.pyplot as plt
import pandas as pd 
import numpy as np 
import glob
import sys 
rally_files= glob.glob("C:/Users/epicr/Downloads/archive/*.txt")
for file in rally_files:
    with open(file, 'r', encoding="UTF-8") as f:
        lines= f.readlines()
        for line in lines:
            for word in line.split('\n'):
                print (word)

输出在这里有效:

word word word word word word word word word word more random words Joe Joe random random Joe

现在,我想遍历我刚刚创建的巨大文本文件中的每个单词并找到一个特定的单词。如果该词存在,我想将其添加到计数器中。假设如果它检测到“乔”这个词,计数器就会上升。下面是我的代码:

from __future__ import print_function
import matplotlib.pyplot as plt
import pandas as pd 
import numpy as np 
import glob
import sys 
rally_files= glob.glob("C:/Users/epicr/Downloads/archive/*.txt")
count=0
for file in rally_files:
    with open(file, 'r', encoding="UTF-8") as f:
        lines= f.readlines()
        for line in lines:
            for word in line.split('\n'):
                if word in line.split('\n')== 'Joe':
                        count +=1
print (count)

它似乎什么都没有。事实上,我知道“乔”这个词已经出现了大约 300 次。有人可以帮帮我吗?

【问题讨论】:

    标签: python string for-loop search count


    【解决方案1】:
    count=0
    for file in rally_files:
        with open(file, 'r', encoding="UTF-8") as f:
            lines= f.readlines()
            for line in lines:
                count += line.count("Joe")
    

    【讨论】:

    • 介意你解释一下你的答案,这是如何解决问题的?干杯!
    猜你喜欢
    • 2019-02-21
    • 2012-10-31
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多