涉及“TypeError:期望的字符串或类字节对象”的Python正则表达式问题

时间:2017-04-04 03:47:12

标签: regex python-3.x typeerror

我在标题中遇到涉及类型错误的问题,代码如下:

def testregex():
    import re

inputfilename = input("Enter Input File Name: ")
keyword = input("Enter Keyword: ")
outputfilename = input("Enter Output File Name: ")

pattern = re.escape(keyword) + r"[\s\n]+([\w\.]+)\s+(\w+)\s+(\w+)[\s\n]+(\d+\s\w+\s\w+)[\s\n]+(\w+\s?\w+,\s\w+\s\d+)"

inputfile = open(inputfilename, "r")
outputfile = open(outputfilename, "w")

match = re.findall(pattern, inputfile)
if match:
    for tuple in match:
        outputfile.write(tuple[0]+ " " + tuple[1]+ " " + tuple[2] + "\n" +tuple[3]+ "\n" +tuple[4] + "\n")

inputfile.close()
outputfile.close()

如图所示使用参数运行多次,无论如何我仍然会收到以下错误:

Enter Input File Name: lettersinput.txt

Enter Keyword: Sincerely,

Enter Output File Name: Lettersoutput2.txt
Traceback (most recent call last):

  File "<ipython-input-32-32667d9b5684>", line 13, in <module>
    match = re.findall(pattern, inputfile)

  File "/Users/Jmsquillaro/anaconda/lib/python3.5/re.py", line 213, in findall
    return _compile(pattern, flags).findall(string)

TypeError: expected string or bytes-like object

我做错了什么,可以修复什么而不会使代码过于复杂?该脚本应该找到一个输入文件,在其上执行列出的正则表达式,并将结果作为元组插入到用户标题的新输出文件中。作为参考,运行此代码时,将创建输出文件,但该文件为空。此外,还有什么我可以做的,以使这次运行更顺畅,并避免任何其他可预见的问题?非常感谢你!

0 个答案:

没有答案