python 删除txt文件,使用Python从txt文件中删除字符

I'm writing a program in python that will request a user to input a file name, open the file, and count the number of M's and F's and tally it as a ratio. I can get it to do that, and remove whitespace, but I can't figure out how to remove characters that are not M or F. I want to remove all incorrect characters and write them in a new file. Here's what I have so far

fname = raw_input('Please enter the file name: ') #Requests input from user

try: #Makes sure the file input is valid

fhand = open(fname)

except:

print 'Error. Invalid file name entered.'

exit()

else:

fhand = open(fname, 'r') #opens the file for reading

entireFile = fhand.read()

fhand.close()

entireFile.split() #Removes whitespace

''.join(entireFile) #Rejoins the characters

entireFile = entireFile.upper() #Converts all characters to capitals letters

males = entireFile.count('M')

print males

females = entireFile.count('F')

print females

males = float(males)

females = float(females)

length = males + females

print length

length = float(length)

totalMales = (males / length) * 1

totalFemales = (females / length) * 1

print "There are %", totalMales, " males and %", totalFemales, " in the file."

解决方案

Use a regular expression to extract all characters that are not M or F:

import re

remainder = re.sub(r'M|F', '', entireFile)

with open('new_file', 'wb') as f:

f.write(remainder)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值