【问题标题】:How to find words inside two text files如何在两个文本文件中查找单词
【发布时间】:2016-01-04 23:18:09
【问题描述】:

脚本的第一部分没问题(它删除了http://www.)。稍后我需要检查 source 中的单词是否存在于存在。

source = open('/net/sign/temp/python_tmp/script1/source.txt','r')
exists = open('/net/sign/temp/python_tmp/script1/exists.txt','r')

with source as f:
        lines = f.read()
        lines = lines.replace('http://','')
        lines = lines.replace('www.','')

        for a in open('/net/sign/temp/python_tmp/script1/exists.txt'):
            if a == lines:
                print("ok")

source.txt的内容:

www.yahoo.it
www.yahoo.com
www.google.com
http://www.libero.it

exists.txt的内容:

www.yahoo.com

【问题讨论】:

  • 完全不清楚您要做什么。您是否需要查找两个文件中存在的所有单词?你对一个词的定义是什么?区分大小写怎么办?另外我不认为read 正在做你期望它做的事情,否则你不会调用返回值lines
  • 为什么你 open exists.txt 文件两次?
  • 首先,您必须将单词提取到一些数据结构中(我相信集合会很完美)。目前您只操作线条。然后你必须比较这些集合是否相交。你清楚怎么做吗?
  • 您能否提供一些source.txtexists.txt 文件的示例内容?
  • if ("http://" and "www.") in a: ?

标签: python string


【解决方案1】:

这样的事情应该可以工作:

source_words = set()
with open('source.txt') as source:
    for word in source.readlines():
        source_words.add(word.replace('http://','').replace('www.','').strip())

exist_words = set()
with open('exist.txt') as exist:
    for word in exist.readlines():
        exist_words.add(word.replace('http://','').replace('www.','').strip())

print("There {} words from 'source.txt' in 'exists.txt'".format(
   "are" if exist_words.intersection(source_words) else "aren't"
))

如果您需要获取两个文件中都存在的确切单词,它们在交集结果中:

print("These words are in both files:")
for word in exist_words.intersection(source_words):
    print(word)

【讨论】:

    【解决方案2】:

    好的,从您的示例文件来看,您实际上想要做的是找到两个文本文件共享的行。如果您的文件不是很大,一个简单的解决方案是读取文件并计算它们的行集的交集。

    >>> with open('source.txt') as s, open('exists.txt') as e:
    ...     result = set(s).intersection(e)
    ... 
    >>> result
    set(['www.yahoo.com\n'])
    

    之后您可以将'http://''www.' 替换为

    result = [x.replace('http://', '').replace('www.', '') for x in result]
    

    如果你愿意的话。

    【讨论】:

    • 不知道您可以使用with 打开多个文件。不错的答案。 :)
    • @erip 它只会对未知数量的文件变得有点棘手:)
    • 你正在无缘无故地创建一个集合和两个列表stackoverflow.com/questions/34588974/…
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 2021-11-07
    相关资源
    最近更新 更多