【发布时间】: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 中唯一出现的名字。
如何找到相同的事件而不是文件中的差异?
【问题讨论】:
-
有什么问题/疑问?
-
已更新,感谢反馈!
-
这肯定有人问过。如果您搜索一下,您会找到答案:)
-
既然你有集合,我认为你应该能够与
&运算符进行交集。 docs.python.org/3.8/library/…
标签: python