我想搜索一个带有句子的文件,然后把带有特定单词的句子拿出来。我写了这段代码就是为了做到这一点。
def finding(q):
for item in sentences:
if item.lower().find(q.lower()) != -1:
list.append(item)
for sentence in list:
outfile.write(sentence+'\r\n')
finding('apple')
finding('banana')问题是这样可以找到子字符串而不是单词。例如,“苹果树是大的”这句话。也会被提取。
发布于 2013-12-21 16:10:46
将行拆分成单词;最简单的方法是使用str.split()
for line in sentences:
if any(q.lower() == word.lower() for word in line.split()):
outfile.write(line + '\n')您也可以添加一个.strip('?!."()')来删除最常见的标点符号。
请注意,在文本模式下打开的Python,如果您写出一个\r\n,就已经在\n上使用了。上面的代码还直接将匹配的行写入输出文件。
或者,使用正则表达式查找匹配:
import re
def finding(q, sentences, outfile):
pattern = re.compile(r'\b{}\b'.format(re.escape(q), flags=re.IGNORE)
for line in sentences:
if pattern.match(line)
outfile.write(line + '\n')re.IGNORE使匹配忽略大小写,\b添加单词边界,re.escape()从输入查询中删除任何表达式元字符。
发布于 2013-12-21 16:31:42
另一种选择:
sentences = [
'this has a banana',
'this one does not',
'bananatree should not be here',
'go go banana go'
]
import re
found = filter(re.compile(r'\bbanana\b', flags=re.I).search, sentences)
# ['this has a banana', 'go go banana go']https://stackoverflow.com/questions/20720898
复制相似问题