How do I match a word in a text file using python?

前端 未结 5 1765
青春惊慌失措
青春惊慌失措 2021-01-13 03:58

I want to search and match a particular word in a text file.

with open(\'wordlist.txt\', \'r\') as searchfile:
        for line in searchfile:
            if         


        
5条回答
  •  春和景丽
    2021-01-13 04:40

    You can always use regex, something along the lines of:

    import re
    
    with open('wordlist.txt', 'r') as searchfile:
            for line in searchfile:
                if re.search( r'\sthere\s', line, re.M|re.I):
                        print line
    
    • \sthere\s - any space followed by 'there' followed by any space
    • re.I - means case insensitive
    • re.M - doesn't really matter in this case (since lines only have 1 \n)

提交回复
热议问题