나는 파일 이름을 입력하고, 파일을 열고, M과 F의 수를 세고 비율로 집계 할 것을 요구하는 프로그램을 파이썬으로 작성하고있다. 나는 그것을 할 수 있고 공백을 제거 할 수 있지만 M이나 F가 아닌 문자를 제거하는 방법을 알 수는 없다. 잘못된 문자를 모두 제거하고 새 파일에 쓰기를 원한다.파이썬을 사용하여 txt 파일에서 문자 제거하기
import re
data = re.findall(r'[FM]', entirefile)
을 당신이 사용하는 경우 r'[FMfm]'
는 대문자로 모든 파일이 필요하지 않습니다, 정규식 모두 잡을 것 : 여기에 지금까지
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."
왜 한 번에 파일의 내용을 반복하고 각 문자에 대한 작업을 수행하지 : –
코드 개선과 이해를위한 제 제안 : 1)'split'은 모든 공백을 제거하고, 단지 (효과적으로) 개행을 제거하지 않습니다. 2)'fhand'를 두 번 열었습니다. 이것은 중복되어서 원래의'fhand'을 열어 둘 수 있습니다. 파일을 두 번 열지 않아도되는 해결책은 http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python을 참조하거나, 당신이 만드는 첫 번째'fhand'를 사용하십시오. 3) 예외를 쳤을 때 당신이 exit()를했기 때문에 거대한'else'에 코드를 넣는 것은 필요하지 않습니다. –