从文件中删除数字

时间:2013-07-17 07:05:57

标签: python

我有一个以下形式的文件:

car1 auto1 automobile1 machine4 motorcar1
bridge1 span5
road1 route2

但我想删除整数,以便我的文件看起来像:

car auto automobile machine motorcar
bridge span
road route

我试图逐个字符地读取文件,如果字符是数字,则跳过它。但是我将它们打印在一个新文件中。如何在输入文件中进行更改?

5 个答案:

答案 0 :(得分:9)

使用regular expressions

import re
import fileinput

for line in fileinput.input("your_file.txt", inplace=True):
    print re.sub("\d+", "", line),

注意:fileinput是一个处理文件的好模块。

编辑:为了获得更好的性能/更低的灵活性,您可以使用:

import fileinput
import string

for line in fileinput.input("your_file.txt", inplace=True):
    print line.translate(None, string.digits),

对于多次编辑/替换:

import fileinput
import re

for line in fileinput.input("your_file.txt", inplace=True):
    #remove digits
    result = ''.join(i for i in line if not i.isdigit())
    #remove dollar signs
    result = result.replace("$","")
    #some other regex, removes all y's
    result = re.sub("[Yy]+", "", result)
    print result,

答案 1 :(得分:2)

with open('input.txt', 'r') as f1, open('output.txt', 'w') as f2:
    f2.write("".join([c for c in f1.read() if not c.isdigit()]))

答案 2 :(得分:1)

with open('myfile.txt') as f:
    data = ''.join(i for i in f.read() if not i.isdigit())

with open('myfile.txt', 'w') as f:
    f.write(data)

答案 3 :(得分:1)

使用with读取/写入文件,使用str.translate函数将数字替换为空字符串。见这里:http://docs.python.org/2/library/stdtypes.html#str.translate

with open('file', 'r') as f:
    data = f.read()
data = data.translate(None, '0123456789')
with open('file', 'w') as f:
    f.write(data)

答案 4 :(得分:0)

fpath = '/path/to/your/file'
outpath = '/path/to/your/output/file'
f = open(fpath)
content = f.read()

new_content = ''

for letter in content:
    try:
        int(letter)
    except:
        new_content += letter

outf = open(outpath, 'w')
outf.write(new_content)
outf.close()
f.close()