在Python中使用grep仅搜索确切的单词
我正尝试在Python中使用grep来搜索文本文件中的单词。 我尝试了这样的事情 -
subprocess.call(['/bin/grep', str(word), "textFile.txt"])
这一行是在控制台上打印所有输出。 而且,即使单词不完全匹配,它也会返回true。 例如,即使对于这个匹配,它也会返回一个单词 - xxxwordsxxx
def find_words(in_file, out_file):
for word in in_file:
word = word.rstrip()
subprocess.call(["grep", "-w", word, "textFile.txt"])
编辑我的in_file和textFile.txt是一样的。
我如何实现搜索确切的单词? 如果这不是一个正确的方法,有没有其他方法可以做这个搜索? (这是一个巨大的文本文件,我必须找到文件中所有单词的重复项)
尝试使用参数-w:
import subprocess
word = input("select word to filter: ")
subprocess.call(['/bin/grep', "-w", word, "textFile.txt"]) #str is not needed
链接地址: http://www.djcxy.com/p/78321.html