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

2024-09-30 18:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个包含多个字符串的文件,fileA.txtfileB.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")

任何协助都将不胜感激


Tags: 文件字符串intxthelloforasopen
3条回答

一个简单的解决方案是为每个文件构造一个不同单词的列表,并检查常用单词

在这种情况下,Python的Set数据类型将非常有用。 https://docs.python.org/3.6/library/stdtypes.html#set

文件按迭代,而不是按迭代。你得分词:

>>> 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

首先要获得fileA中所有唯一字符串的列表。然后为fileB获得一个类似的唯一列表。然后比较两者。使用set使比较更容易

def get_strings_from_file(f):
    return set([s.strip() for s in f.read().split() if s.strip()])

def main():
    with open("fileA.txt", 'r') as fileA, open ("fileB.txt") as fileB:
        stringsA = get_strings_from_file(fileA)
        stringsB = get_strings_from_file(fileB)
        return stringsA.intersection(stringsB)

相关问题 更多 >