我有这个代码来搜索文件中的单词(而不是子字符串)并返回找到单词的行:
def word_search(word, file):
pattern = re.compile(r'\b{}\b'.format(re.escape(word), flags=re.IGNORECASE))
return (item for item in file
if pattern.match(item) == -1)
但是这段代码(几乎)回馈了所有东西。我究竟做错了什么? 谢谢你的关注
这是代码:
sentences = re.split(r' *[\.\?!][\'"\)\]]* ]* *', text) # to split the file into sentences
def finding(word, file):
pattern = re.compile(r'\b{}\b'.format(re.escape(word)), flags=re.IGNORECASE)
return (item for item in file if pattern.search(item)) # your suggestion
from itertools import chain # I'm plannig on using more words, and I dont want duplicate #sentences. Thats why i use the chain + set.
chain = chain.from_iterable([finding('you', sentences), finding('us', sentences)])
plural_set = set(chain)
for sentence in plural_set:
outfile.write(sentence+'\r\n')
这给了我你在下面看到的结果。
这是testfile的内容:
“好吧,沃伦太太,我看不出你有什么特别的原因 因为不安,我也不明白为什么我的时间属于某些人 价值,应干涉此事。我还有其他的事情要做 和我说话。“所以说了夏洛克福尔摩斯,然后又回到了伟大的地方 剪贴簿,他正在安排和索引他最近的一些 材料 但是,女房东有顽固性和狡猾性。 她坚定地坚持着自己的立场。 “你去年为我的一个房客安排了一件事,”她说 说 - “Fairdale Hobbs先生。” <啊>“啊,是的 - 这很简单。”“但他永远不会停止谈论它 - 你的善意,先生和 你把光带入黑暗的方式。我记得他的 我自己怀疑和黑暗的话。我知道你可以 你只会。“
福尔摩斯可以在奉承的一面,也可以做他 正义,在仁慈的一面。这两股力量使他平静下来 叹了口气叹了口气,然后推开他的椅子。
代码返回的内容:
沃伦,我看不出你有什么特别的原因 不安,我也不明白为什么我的时间有些价值, 应该干涉这件事所以说Sherlock Holmes然后转过身来 回到他正在安排和编制索引的好剪贴簿 他最近的一些材料。 但是,女房东有顽固性和狡猾性。 她坚定地坚持着自己的立场。 “你去年为我的一个房客安排了一件事,”她说 说 - “Fairdale Hobbs先生。” <啊>“啊,是的 - 这很简单。”“但他永远不会停止谈论它 - 你的善意,先生和 你把光带入黑暗的方式我知道你可以 你只会。“
福尔摩斯可以在奉承的一面,也可以做他 正义,善良的一面
答案 0 :(得分:3)
有三个错误:
None
,而不是-1
。re.search()
而不是re.match()
。flags
参数:所以它应该是这样的:
def word_search(word, file):
pattern = re.compile(r'\b{}\b'.format(re.escape(word)), flags=re.IGNORECASE)
return (item for item in file if pattern.search(item))
让我们看看它的实际效果:
>>> file = ["It's us or them.\n",
... '"Ah, yes--a simple matter."\n',
... 'Could you hold that for me?\n',
... 'Holmes was accessible upon the side of flattery, and also, to do him justice, upon the side of kindliness.\n',
... 'Trust your instincts.\n']
>>> list(word_search("us", file))
["It's us or them.\n"]
>>> list(word_search("you", file))
['Could you hold that for me?\n']