Python - 打印存在于2个文件中的字符串

Yun*_*ter 2 python file python-3.x

我有2个文件包含多个字符串,fileA.txtfileB.txt.

fileA.txt:

hello hi 
how
Run Code Online (Sandbox Code Playgroud)

fileB.txt:

hello how are you
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个程序,看看两个文件中是否存在字符串.如果是,则打印字符串或多个字符串.

结果将在两个文件中打印"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")
Run Code Online (Sandbox Code Playgroud)

任何援助将不胜感激.

wim*_*wim 5

文件按而不是单词迭代.你必须分开这些词:

>>> with open('fileA.txt') as a, open('fileB.txt') as b:
...     a_words = set(a.read().split())
...     b_words = set(b.read().split())
...     print('\n'.join(a_words & b_words))
...     
hello
how
Run Code Online (Sandbox Code Playgroud)