我有一个文本文件,需要用空格替换数字。
我尝试先将文本文件拆分为单个单词,然后检查该单词是否为数字
def replace_digits_symbols():
text_file = open_file()
for word in text_file:
for char in word:
if char.isdigit():
word.replace(char, " ")
print(text_file)
应该用空格代替它们,但什么也没发生
答案 0 :(得分:0)
str.replace
方法仅返回替换的字符串,而无需就地更改原始字符串,这就是为什么调用word.replace(char, " ")
不会执行任何操作的原因。相反,您可以将str.join
与生成器表达式一起使用,该表达式迭代一行中的每个字符并输出空格而不是原始字符(如果它是数字):
with open('file') as file:
for line in file:
print(''.join(' ' if char.isdigit() else char for char in line))
答案 1 :(得分:0)
这是此过程的完整代码,
def helper(text):
import string
for digit in string.digits:
text = text.replace(digit, ' ')
return text
def ReplaceDigits(fileName):
output_file = open("processed.txt",'w')
lineNo = 1
with open(fileName) as file_ptr:
for lines in file_ptr:
print("Processing Line No : {}".format(lineNo))
lines = helper(lines)
output_file.write(lines)
lineNo +=1
ReplaceDigits("test.txt")
test.txt包含
this1is5sample0text
this10is552sample0text
this10is5sample0text
this10is52sample0text
this0is52sample0text
结果是
this is sample text
this is sample text
this is sample text
this is sample text
this is sample text