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

穿精又带淫゛_ 提交于 2021-02-17 06:11:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!