【问题标题】:Reading and writing text files while checking occurrences在检查事件时读取和写入文本文件
【发布时间】:2020-01-21 00:03:46
【问题描述】:

我正在尝试从名为first-names.txt 的文本文件中读取名称,并查看它们是否存在于oliver-twist.txt 中。

到目前为止,我已经能够使用以下代码将不在oliver-twist.txt 中但存在于first-names.txt 中的名称输出到occurrences.txt

with open('first-names.txt', 'r')as f:
    d = set(f.readlines())

with open('oliver-twist.txt', 'r') as f:
    e = set(f.readlines())

with open('occurrences.txt', 'a') as f:
    for line in list(d-e):
        f.write(line)

来自oliver-twist.txt的片段:

This resistance only infuriated Mr. Sikes the more; who, dropping on
his knees, began to assail the animal most furiously.  The dog jumped
from right to left, and from left to right; snapping, growling, and
barking; the man thrust and swore, and struck and blasphemed; and the
struggle was reaching a most critical point for one or other; when, the
door suddenly opening, the dog darted out:  leaving Bill Sikes with the
poker and the clasp-knife in his hands.

来自first-names.txt的片段:

Aaron
Aaron
Abbey
Abbie
Abby
Abdul
Abe
Abel
Abigail
Abraham
Abram
Ada
Adah
Adalberto
Adaline
Adam
Adam
Bill

预期的输出应该是:

Bill

因为 Bill 是 oliver-twist.txt 中唯一出现的名字。 如何找到相同的事件而不是文件中的差异?

【问题讨论】:

标签: python


【解决方案1】:

这样的事情应该可以工作:

with open('first-names.txt') as f:
    first_names = f.readlines()

with open('oliver-twist.txt') as f:
    oliver_twist = f.read()

for name in first_names:
    if name in oliver_twist:
        print(name)

【讨论】:

  • 这正是我想要的!谢谢。
【解决方案2】:

您可以对从文本文件中导入的两组进行理解,我在您的示例中添加了更多名称进行测试,所有名称看起来都可以检测到。

在此处使用条删除导入的\n,如果文件中没有新行,则可能不需要它。

with open('first-names.txt', 'r')as f:
    d = set(f.readlines())

with open('oliver-twist.txt', 'r') as f:
    e = set(f.readlines())

result = [name.strip() for name in d for sentence in e if name.strip() in sentence]

#['Abram', 'Ada', 'Adah', 'Bill', 'Adam']

我将所有名称添加到 oliver-twist.txtbillfirst-names.txt,因为示例中没有匹配项。

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多