【问题标题】:Python: Error:TypeError: findall() missing 1 required positional argument: 'string'Python:错误:TypeError:findall()缺少1个必需的位置参数:'string'
【发布时间】:2019-02-02 18:52:52
【问题描述】:

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

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 个必需的位置参数: '字符串'

【问题讨论】:

  • 您没有使用包含要搜索正则表达式的文本的linevariable。提问前请参考rere.findall的文档。

标签: regex python-3.x


【解决方案1】:

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

这就是你想要的答案:

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)

关于正则表达式,听起来像这样post might help
TL;DR:
你可以使用这个正则表达式:

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

【讨论】:

  • 谢谢!它只返回[]有什么原因吗?我在文本文件中有 10000 个名字。许多人有信件。但是,我想排除那些有特殊字符(除了-)
  • 发生这种情况是因为您的正则表达式没有“抓住”任何东西。你需要修复你的正则表达式......我不确定你试图实现什么,但我编辑了我的答案给你一些链接
  • 感谢您的帮助。 :) 我正在尝试过滤掉文档中的所有非名称。我还没有完成代码,但希望最终将所有非名称发送到一个 csv 文件,并将所有实际名称发送到另一个 csv 文件。我设法让它读取整行,但它没有过滤掉非名称。新代码:lines = open(r"C:\Users\Vincent\Documents\python\theSortingHat\100000DirtyNames.txt").readlines() #open text file for line in lines: #iterate through every line #return list of names在那一行 if re.search(r"[a-zA-Z]+", line): print(line, end="")
  • 我想,这就是为什么我给了你那个正则表达式和一个指向我从中获取的帖子的链接。 SO中有一个接受答案的东西,通过单击相关答案旁边的绿色箭头来使用它
  • 可能值得注意的是x != 0 将始终为真,因为re.findall 返回的是字符串列表,而不是数字。也许只是if x?如果x == [],那至少会失败。
猜你喜欢
  • 2021-05-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2020-10-19
  • 1970-01-01
相关资源
最近更新 更多