你是不是佔換行符或空格:
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
用空字符串替換各種空格。
另一種選擇是使用all
與str.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())))
標準開發和中位數我會離開你自己弄清楚。
謝謝!當我嘗試寫這個時,我得到一個錯誤,說我不能:In []和內容之間? – Ella
@Ella,你必須做錯了,因爲答案和輸出中的代碼是從ipython會話運行的,應該沒有錯誤 –
@Ella,你也有問題標記爲python3,但是你正在使用python2的raw_input,所以什麼是你真的在用嗎? –