Using grep in Python to search for exact words only
I am trying to use grep in Python to search for words in a text file. I tried something like this -
subprocess.call(['/bin/grep', str(word), "textFile.txt"])
This line is printing all output on console. Also, it is returning true even if the word is not matching exactly. For example, it returns a word even for this match - xxxwordsxxx
def find_words(in_file, out_file):
for word in in_file:
word = word.rstrip()
subprocess.call(["grep", "-w", word, "textFile.txt"])
edit My in_file and textFile.txt are the same.
How do I implement a search for the exact word? If this is not a correct way, is there any other way I could do this search? (It is a huge text file and I have to find duplicates of all the words in the file)
尝试使用参数-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/78322.html