使用Python从txt文件中删除字符 [英] Removing characters from a txt file using Python

查看:748
本文介绍了使用Python从txt文件中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用python编写一个程序,该程序将要求用户输入文件名,打开文件,并计算M和F的数量并将其作为比率进行计数。我可以做到这一点,并删除空格,但是我不知道如何删除非M或F的字符。我想删除所有不正确的字符并将其写入新文件。这就是我到目前为止的情况

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."


推荐答案

使用正则表达式提取所有非M或F:

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)

这篇关于使用Python从txt文件中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆