【问题标题】:Finding strings from list in lines of text从文本行中的列表中查找字符串
【发布时间】:2020-01-31 16:51:02
【问题描述】:

我想从 res 列表中获取那些具有字符串的行(其中至少 4 个,o 一个 O 代替零)以及名称。使用下面的脚本,我得到没有名称的新行,只有行有 0 和 1。

我有一个包含如下名称和数字行的文本文件:

txt 文件中的行:

John Johns 1-1, 1-2
Adam Adams 1:0, 2:0
Dave Davis 1-0, 1:1
Jim Jims   1_0 1_1
Tim Tims 0 0 0 1
Tom Toms 2-0, 3:2
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11


res = ['1', '0', 'o', 'O', '1', '1']

with open('txt_file.txt') as oldfile, open('new_txt.txt', 'w') as newfile:
    for x in res:
        for line in oldfile:
            line_new = [x for x in res if (x in line)]
            line = ''.join(line_new)
            newfile.write(line)

新文件中的预期行

Dave Davis 1-0, 1:1
Jim Jims   1_0 1_1
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11

【问题讨论】:

  • 明确更换规则
  • list 文字中缺少逗号。
  • 已编辑,粘贴和格式化时出错。

标签: python python-3.x list


【解决方案1】:

不要使用模棱两可的列表,而是使用以下基于特定正则表达式模式的简洁方法:

import re

with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
    num_pat = re.compile(r'\b1[:.,_\s-]?[0oO],?\s+1[:.,_\s-]?1$')
    for line in f_in:
        if num_pat.search(line):
            f_out.write(line)

最后的output.txt内容:

Dave Davis 1-0, 1:1
Jim Jims   1_0 1_1
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11

【讨论】:

  • 你能简单解释一下这行是什么:\b1[:.,_\s-]?[0oO],?\s+1[:.,_\s-]? 1$ 如果文本文件中的数字不是 1 和 0 怎么办?感谢您的宝贵时间!
  • @hoppdev,老实说,一段时间以来,我在 SO 上添加的答案越多 - 他们就越被忽视和忽视。我看到了这种“偏见”的趋势
  • 感谢您向我指出特定的正则表达式模式,作为初学者,我对这种方法一无所知。最后,经过一些学习,我设法用简单的一行回答了我的另一个问题:1.*?[0oO].*?1.*?1.*?
【解决方案2】:

我很确定一些线程已经回答了这个问题,因为它基本上是字符串匹配的列表。

你已经可以查看这个了:how-to-check-if-a-string-contains-an-element-from-a-list-in-python

或者这个:check-list-of-words-in-another-string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 2023-03-24
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多