输入:我想获取包含内容的.txt文件(请参阅下面的.txt文件中的示例内容)
soccerfif@yahoo.com 366-44-4444 Jezos was born Jeffrey Preston Jorgensen on January 12, 1964, also 5 and 4
过程:我想通过Def函数(replace_numbers)运行它
输出:我希望附加通过该函数运行的文件,以删除所有数字(请参见下面的示例)
soccerfif@yahoo.com 366-44-4444 Jezos was born Jeffrey Preston Jorgensen on January 12, 1964, also and
这是我的代码:
import re
theFile=open("/home/file/wow.txt",'rt', encoding= 'latin-1').read()
words=theFile.split()
def replace_numbers(words):
new_words=[]
for word in words:
pattern= re.compile(" \d+")
if pattern.match(1):
new_word= re.sub(pattern, " ", word)
new_words.append(new_word)
return new_words
r=replace_numbers(words)
print(r)
Ran我运行了这段代码,但出现错误:预期的字符串或类似字节的对象
关于如何使用def函数对文件执行此操作的任何建议。
答案 0 :(得分:1)
这就是我要做的:
theFile = open ("wow.txt",'rt', encoding= 'latin-1').read()
words = theFile.split()
def replace_numbers (words) :
exclude_list = [str (x) for x in range (10)]
new_words = []
for word in words :
if word not in exclude_list :
new_words.append (word)
return new_words
r = replace_numbers (words)
print (r)