脚本的第一部分是正常的(它删除了http://
和www.
)。稍后我需要检查源内的单词是否存在。
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
答案 0 :(得分:4)
这样的事情应该有效:
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)
答案 1 :(得分:3)
好的,从您的示例文件判断您实际要做的是查找两个文本文件共享的行。如果你的文件不是巨大的,一个简单的解决方案是读取文件并计算它们的行集的交集。
>>> 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]
如果你愿意的话。