【问题标题】:How to return up to five occurrences of a string in a text file?如何在文本文件中返回最多五次出现的字符串?
【发布时间】:2017-11-18 13:55:40
【问题描述】:

我的任务涉及用户输入字符串。然后我的程序需要从一个文本文件中返回最多五次出现的该字符串,然后将这些行保存到一个单独的文件中。

这是我的代码: My code

但是,我不知道如何更改它,以便它返回最多 5 次出现的字符串,仅此而已。

非常感谢,AB

【问题讨论】:

  • 请在您的问题中包含代码,而不是指向可能过期的图像的链接。

标签: python python-3.x file search text


【解决方案1】:

初始化一个计数器并加到五个。五点钟退出……

Count=0
for line is search_file:
    if searchspec in line:
        #write to file
        Count+=1
    if count == 5:
        break

【讨论】:

    【解决方案2】:

    试试这个,

    import re
    
    input_string = input("Search Criteria : ")
    
    with open('textfile.txt', 'r') as input_file:
    
    data = input_file.read()
    
    if len(re.findall(input_string, data)) == 5:
    
        for line in data.split('\n'):
    
            if input_string in line:
    
                with open('fiveoccurrences.txt', 'a+') as out_file:
    
                    out_file.write(line+'\n')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多