关于正则表达式:Python:错误:TypeError:findall()缺少1个必需的位置参数:“字符串”

Python: Error:TypeError: findall() missing 1 required positional argument: 'string'

我正在尝试使用特定参数来清理文本文档。 尝试了x=...行的不同迭代,但是该程序无法读取所有行。

1
2
3
4
5
6
7
8
9
10
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)

我收到:

Error:TypeError: findall() missing 1 required positional argument:
'string'


您需要在字符串中查找内容。 问题是您只给了re.findall一个参数,还应该给line作为参数。
您的正则表达式也遇到了一些问题,您没有关闭组(即()),这导致它成为无效的正则表达式。

这是您的目标答案:

1
2
3
4
5
6
7
8
9
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)

关于正则表达式,听起来像这篇文章可能会有所帮助
TL; DR:
您可以使用此正则表达式:

1
^[A-Z]'?[- a-zA-Z]+$