擅长:python、mysql、java
<p>这将检索<code>words</code>中出现的每个单词的索引,该索引是文件中所有单词的列表。然后使用切片来获得匹配单词和前后5个单词的列表。在</p>
<pre><code>def occurs(word, filename):
infile = open(filename,'r')
lines = infile.read().splitlines()
infile.close()
wordsString = ''.join(lines)
words = wordsString.split()
matches = [i for i, w in enumerate(words) if w.lower().find(word) != -1]
for m in matches:
l = " ".join(words[m-5:m+6])
print(f"... {l} ...")
</code></pre>