简体   繁体   中英

Why does this code give me an error?

I have this code:

import re
with open("text2.txt", "r") as f:
    content = f.readlines()
numbers = re.findall(r'\b\d{3}\b', content)
with open("text3.txt", "w") as f:
    f.write(str(numbers))

When run, it's supposed to find all of the three digit numbers, and print them to a new text file.

When I run it, I get this error:

Traceback (most recent call last):
  File "C:\Users\Zach\Desktop\test3.py", line 4, in <module>
    numbers = re.findall(r'\b\d{3}\b', content)
  File "C:\Panda3D-1.7.2\python\lib\re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

What am I doing wrong?

re.findall expects a string as its second argument, but the readlines method of a file object returns a list. Perhaps you meant to use the read method instead (which returns a string):

with open("text2.txt", "r") as f:
    content = f.read()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM