问题
I am trying to scrub a text document with specific parameters. Have tried different iterations of the x=...
line but the program isn't able to read the all line.
import re
#import csv
text = open(r'C:\Users\Vincent\Documents\python\theSortingHat\100000DirtyNames.txt') #open text file
for line in text: #iterate through every line
#return list of names in that line
x = re.findall ('^([a-zA-Z]-?$')
#if an actual name is found
if x != 0:
print(x)
I receive:
Error:TypeError: findall() missing 1 required positional argument: 'string'
回答1:
You need to find something in a string. The problem is that you gave re.findall
only the one parameter, you should also give line
as a parameter.
You also had some problem with your regex and you didn't close your group (i.e. ()
), what made it to a not valid regex.
This is the answer that you are aiming for:
import re
text = open(r'C:\Users\Vincent\Documents\python\theSortingHat\100000DirtyNames.txt') #open text file
for line in text: #iterate through every line
#return list of names in that line
x = re.findall('^([a-zA-Z])-?$', line)
#if an actual name is found
if x != 0:
print(x)
About the regex, sounds like this post might help
TL;DR:
you can use this regex maybe:
^[A-Z]'?[- a-zA-Z]+$
来源:https://stackoverflow.com/questions/54496411/python-errortypeerror-findall-missing-1-required-positional-argument-stri