我有两个包含多个字符串的文件,fileA.txt
和fileB.txt
fileA.txt:
hello hi
how
fileB.txt:
hello how are you
我试图写一个程序,看看是否字符串存在于两个文件。如果有,打印字符串或多个字符串
结果将打印“hello”和“how”,因为它们存在于两个文件中
执行此操作时遇到问题,因为我只能处理我定义的字符串,而不是文件中未知的字符串:
with open("fileA.txt", 'r') as fileA, open ("fileB.txt") as fileB:
for stringsA in fileA:
for stringsB in fileB:
if stringsA in stringsB:
print("true")
任何协助都将不胜感激
一个简单的解决方案是为每个文件构造一个不同单词的列表,并检查常用单词
在这种情况下,Python的Set数据类型将非常有用。 https://docs.python.org/3.6/library/stdtypes.html#set
文件按行迭代,而不是按字迭代。你得分词:
首先要获得
fileA
中所有唯一字符串的列表。然后为fileB
获得一个类似的唯一列表。然后比较两者。使用set
使比较更容易相关问题 更多 >
编程相关推荐