首页 > 解决方案 > 如果我放一个像 s=1234567891 这样的字符串,代码可以工作,但是如果我有一个文本文件“yesno.txt”,其中有数据,则会出错

问题描述

如果我在代码本身中有一个字符串,我的代码就可以完美运行,例如:

"s= my number is 1234567891" 

但是当我的文本文件(yesno.txt)中有相同的文本时,我遇到了一个错误:

import re

def getphonenumber(s):
   phonenumberregex=re.compile(r'\+\d\d\d\d\d\d\d\d\d\d\d\d|\d\d\d\d+-\d\d\d\d\d\d\d|\d\d\d\d\d\d\d\d\d\d')
   matchobject = phonenumberregex.findall(s)
   #print("mobile number -",matchobject.group())  .....use this for printing
   if matchobject:
       return matchobject
   else:
       return None

s = open("yesno.txt","r")     
print(getphonenumber(s))
File "C:/Users/G0002944/.spyder-py3/tryy1.py", line 12, in getphonenumber
    matchobject = phonenumberregex.findall(s)

TypeError: expected string or bytes-like object

此外,我想将该数据传输到数据库中。需要帮助,因为我是 python 新手,在此先感谢。

标签: pythonregex

解决方案


推荐阅读