简体   繁体   中英

How to use a string variable into re.findall?

I used Python to find a word started and ended with specified letters through a text file. But, I have some problem with using a string variable inside re.findall command. Could you please give me any suggestion?

import re
import sys

f = open(sys.argv[1]+'.txt', "r")
data = f.read()
re.findall(r'\b'+str(sys.argv[2])'\w+', data)

Could you please expanding this code to find a word started and ended with defined letters?

What you are looking for is re.compile function, not sure what your code does but with your given example:

import re
import sys
f = open(sys.argv[1]+'.txt',"r")
data = f.read()
regex = re.compile(r"\b" + str(sys.argv[2]) + r"\w+")
re.findall(regex, data)

If you want to get words starting and ending with specified letters you could use something like:

import re
import sys
f = open(sys.argv[1]+'.txt',"r")
data = f.read()
                   # starting with 'a' and ending with 'w'
regex = re.compile("^a" + str(sys.argv[2]) + "w$")
re.findall(regex, data)
import re
import sys

thefile = open(sys.argv[1]+".txt", "r")

for line in thefile:
    if re.match(sys.argv[2]+"(.*)"+sys.argv[3]+"(.*)(.*)", line):
        print line

argv[1] is a file name

argv[2] is a starting letter of word,

argv[3] is a ending letter of word,

you can search a word using starting and ending letter of words

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM