[英]Removing characters from a txt file using Python
我正在用python編寫一個程序,該程序將要求用戶輸入文件名,打開文件並計算M和F的數量,並將其作為比率。 我可以做到這一點,並刪除空格,但是我不知道如何刪除非M或F的字符。我想刪除所有不正確的字符並將其寫入新文件。 這是我到目前為止的
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."
最簡單的方法是使用正則表達式:
import re
data = re.findall(r'[FM]', entirefile)
如果使用r'[FMfm]'
,則不需要將所有文件都大寫,則正則表達式將捕獲所有大寫和小寫字母。
這將返回所有F's
和M's
,而根本不需要刪除white spaces
。
例:
entirefile = "MLKMADG FKFLJKASDM LKMASDLKMADF MASDLDF"
data = ['M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'M', 'F']
您可以使用此列表執行任何操作。
希望這可以幫助。
m,f,other = [],[],[]
for ch in entierFile:
if ch == "M":m.append(ch)
elif ch == "F":f.append(ch)
else: other.append(ch)
print len(m) + " Males, "+len(f)+" Females"
print "Other:",other
使用正則表達式提取所有非M或F的字符:
import re
remainder = re.sub(r'M|F', '', entireFile)
with open('new_file', 'wb') as f:
f.write(remainder)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.