2015-12-01 28 views
1
userinput = raw_input('Write file name:') 

myfile = open(userinput) 

content = myfile.read() 

if content == "": 
    print("Empty file") 
elif content.isalpha(): 
    print("Just letters") 
elif content.isdigit(): 
    print("Numbers") 
else: 
    print("It's both") 

- 當我這樣做,並寫入文本文件,只有數字我總是得到這是兩個,我不知道該怎麼改變。此外,如果任何人都可以幫助我,當腳本發現如果文件只包含字母或數字,我需要找到數字的平均值,中位數,最小值,最大值和標準偏差,我應該怎麼做?試圖讓我的Python腳本,看看文本文件是否只讀取數字或單詞

謝謝!

回答

0

你是不是佔換行符或空格:

In [65]: "abc\n".isalpha() 
Out[65]: False 

In [66]: "133\n".isdigit() 
Out[66]: False 

In [67]: "133 123".isdigit() 
Out[67]: False 

如果數據是單行沒有空格使用content.rstrip()

In [70]: "abc\n".rstrip().isalpha() 
Out[70]: True 

如果有空間,那麼你將不得不決定你認爲字母或全部數字,你可以拆分並重新加入一個沒有空格的字符串,或使用str.translate用空字符串替換各種空格。

另一種選擇是使用allstr.isspace

In [72]: content = "123 123\n" 

In [73]: all(ch.isdigit() or ch.isspace() for ch in content) 
Out[73]: True 

In [74]: content = "foo\nbar\n" 

In [75]: all(ch.isalpha() or ch.isspace() for ch in content) 
Out[75]: True 

你選擇完全什麼取決於你認爲哪些條件才能爲α或通過換行和/或空格資格或分離所有的數字即做多行在一行中只有連續的字符沒有空格。無論哪種方式,你將不得不刪除任何尾隨的換行符,否則你將永遠到達其他人。

如果你正在下降中的所有路線,或爲非常大的文件,我們可以做到這一點的工作,而不讀取所有文件到內存:

import os 


def check_type(user_input): 
    if os.stat(user_input).st_size == 0: 
     return "Empty file" 
    with open(user_input) as my_file: 
     if all(ch.isdigit() or ch.isspace() for line in my_file for ch in line): 
      return "digits!" 
     my_file.seek(0) 
     if all(ch.isdigit() or ch.isspace() for line in my_file for ch in line): 
      return "Alpha" 
     return "Both" 

然後檢查,如果該文件是所有數字和計算平均值爲:

from collections import Counter 
user_input = raw_input('Write file name:') 
if check_type(user_input) == "Digits": 
    with open(user_input) as f: 
     nums = Counter(float(n) for line in f for n in line.split()) 
     print("Average = {}".format(sum(k*v for k,v in nums.items())/sum(nums.values()))) 

標準開發和中位數我會離開你自己弄清楚。

+0

謝謝!當我嘗試寫這個時,我得到一個錯誤,說我不能:In []和內容之間? – Ella

+0

@Ella,你必須做錯了,因爲答案和輸出中的代碼是從ipython會話運行的,應該沒有錯誤 –

+0

@Ella,你也有問題標記爲python3,但是你正在使用python2的raw_input,所以什麼是你真的在用嗎? –

相關問題