0
Searching for a pattern in a text file
Does anybody know why it's not working? file= open("Source_text.txt", "r") pattern1= r'[A-Z][a-z]+' match= re.findall(pattern1,file) I have error that findall expects string or bytes-like object. But when I copy the content from the file directly to the code and assign it to a variable then it works e.g. file= "This is a content of a file." pattern1= r'[A-Z][a-z]+' match= re.findall(pattern1,file) How can I find the pattern without copy the content to code?
1 Answer
+ 2
You have to read the file into a var first and pass that into findall()
pattern = r'[A-Z][a-z]+'
with open ("Source_text.txt", "r") as f:
data = f.read()
match = re.findall(pattern, data, re.M)
# re.M is for multiple lines omit if not needed