2014-03-31 4 views
0

나는 파일 이름을 입력하고, 파일을 열고, 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

왜 한 번에 파일의 내용을 반복하고 각 문자에 대한 작업을 수행하지 : –

+0

코드 개선과 이해를위한 제 제안 : 1)'split'은 모든 공백을 제거하고, 단지 (효과적으로) 개행을 제거하지 않습니다. 2)'fhand'를 두 번 열었습니다. 이것은 중복되어서 원래의'fhand'을 열어 둘 수 있습니다. 파일을 두 번 열지 않아도되는 해결책은 http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python을 참조하거나, 당신이 만드는 첫 번째'fhand'를 사용하십시오. 3) 예외를 쳤을 때 당신이 exit()를했기 때문에 거대한'else'에 코드를 넣는 것은 필요하지 않습니다. –

답변

1

는 M 또는 F가 아닌 모든 문자를 추출하는 정규 표현식을 사용? 예를 들어, 현재 문자가 M 또는 F이면 변수에 하나를 추가하십시오. 그렇지 않으면 현재 파일에서 제거하고 새 파일에 추가하십시오.
+0

afaik 그는 잘못된 문자를 그냥 버리고 싶지 않습니다 ... –

+0

@JoranBeasley 그 점을 지적 해 주셔서 감사합니다. 나는 내 대답을 편집했다 – spinlok

+0

+1 나는 원래의 대답을 잘못 읽었다 : P –

2

가장 쉬운 방법은 정규식을 사용하는 것입니다 무슨이다 대문자와 소문자.

이렇게하면 F'sM's이 모두 반환되므로 white spaces을 전혀 삭제하지 않아도됩니다.

예 : 당신이 목록에 원하는

entirefile = "MLKMADG FKFLJKASDM LKMASDLKMADF MASDLDF" 
data = ['M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'M', 'F'] 

당신이 할 수 있습니다.

희망이 도움이됩니다.

import re 
remainder = re.sub(r'M|F', '', entireFile) 
with open('new_file', 'wb') as f: 
    f.write(remainder) 
1
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 
관련 문제