Python:错误:类型错误:findall() 缺少 1 个必需的位置参数:“字符串" [英] Python: Error:TypeError: findall() missing 1 required positional argument: 'string'
问题描述
我正在尝试使用特定参数清理文本文档.尝试了 x=...
行的不同迭代,但程序无法读取所有行.
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)
我收到:
错误:类型错误:findall() 缺少 1 个必需的位置参数:'字符串'
Error:TypeError: findall() missing 1 required positional argument: 'string'
推荐答案
您需要查找字符串中的某些内容.问题是你只给了 re.findall
一个参数,你还应该给 line
作为参数.您的正则表达式也有问题,并且您没有关闭您的组(即 ()
),这是什么使它成为无效的正则表达式.
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.
这就是你想要的答案:
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;博士:
你可以使用这个正则表达式:
About the regex, sounds like this post might help
TL;DR:
you can use this regex maybe:
^[A-Z]'?[- a-zA-Z]+$
这篇关于Python:错误:类型错误:findall() 缺少 1 个必需的位置参数:“字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!