【问题标题】:number of strings between .txt files.txt 文件之间的字符串数
【发布时间】:2020-12-06 22:17:18
【问题描述】:

我是 Python 新手。我正在查找包含文本文件的已定义文件夹中文本字符串的出现次数。我说的是这个特定字符串的总数。

def errors():
    
    errors = 0
    file = open ("\\d:\\myfolder\\*.txt", "r")
    data = file.read()
    errors = data.count("errors")
    return errors
    print("Errors:", errors)

【问题讨论】:

  • 请展示你的努力。 SO 不是一个工作卸载系统。
  • 对不起,我在上面附上了我现有的代码。
  • 为什么路径的开头有一个\?您不能只使用单个 open 命令打开任意数量的文件并期望 .read() 对其进行排序 - 您需要一次打开一个文件并处理内容,将总数加起来。
  • os.listdir() 可能对您有所帮助,它会返回路径中所有条目的列表,file.readlines() 会返回文本文件中所有行的列表。
  • @FrantisekSchimanski - 如果我的回答有帮助,请投票/接受。如果不是,请解释为什么不。这是 SO 的另一种常见做法。

标签: python string text numbers


【解决方案1】:

你的代码没有任何意义,但如果我理解你想要做什么,那么这里有一些伪代码可以帮助你:

from glob import glob

text_file_paths = glob("\\d:\\myfolder\\*.txt") 
error_counting = 0
for file_path in text_file_paths:
    with open(file_path, 'r') as f:
        all_file_lines = f.readlines()
    error_counting += sum([line.count('errors') for line in all_lines])

print(error_counting)
        

这有帮助吗?

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多