【问题标题】:Python - printing strings that exists in 2 filesPython - 打印存在于 2 个文件中的字符串
【发布时间】:2018-03-01 23:09:54
【问题描述】:

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

文件A.txt:

hello hi 
how

文件B.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 python-3.x file


    【解决方案1】:

    文件按迭代,而不是单词。您必须拆分单词:

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

    【讨论】:

      【解决方案2】:

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

      Python 的 Set 数据类型在这种情况下会很有帮助。 https://docs.python.org/3.6/library/stdtypes.html#set

      【讨论】:

        【解决方案3】:

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

        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)
        

        【讨论】:

        • 感谢您的意见!
        猜你喜欢
        • 2021-10-25
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 2012-08-10
        • 2014-12-14
        • 1970-01-01
        • 1970-01-01
        • 2021-02-24
        相关资源
        最近更新 更多