3

我有一个格式的文件:

car1 auto1 automobile1 machine4 motorcar1
bridge1 span5
road1 route2

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

car auto automobile machine motorcar
bridge span
road route

我正在尝试逐字符读取文件,如果字符是数字,请跳过它。但我将它们打印在一个新文件中。如何更改输入文件本身?

4

5 回答 5

9

使用正则表达式

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,
于 2013-07-17T07:12:18.627 回答
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()]))
于 2013-07-17T07:10:16.263 回答
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)
于 2013-07-17T07:19:04.257 回答
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)
于 2013-07-17T07:29:35.990 回答
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()
于 2013-07-17T07:11:28.210 回答