簡體   English   中英

Python:如何從文件中的行讀取字符並將它們轉換為浮點數和strs,具體取決於它們是數字還是字母?

[英]Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters?

我有一個看起來像這樣的文件:

1 1 C C 1.9873 2.347 3.88776

1 2 C Si 4.887 9.009 1.21

我想逐行閱讀文件的內容。 當我在我使用的線上只有數字時:

for line in readlines(file):
    data = map(float, line.split)

但這只適用於line.split的所有元素都是數字的情況。 我怎樣才能將字母存儲為字符串,將數字存儲為浮點數?

$ cat 1.py
def float_or_str(x):
  try:
     return float(x)
  except ValueError:
     return x

line = '1 1 C C 1.9873 2.347 3.88776'
print map(float_or_str, line.split())

$python 1.py
[1.0, 1.0, 'C', 'C', 1.9873, 2.347, 3.88776]
for line in infile:
    data = [x if x.isalpha() else float(x) for x in line.split()]

如果您的數據包含既不是字母也不是有效浮點數的字段(例如,“A1”),則會出現問題。 您的數據似乎沒有您所說的那些,但如果確實如此,Igor建議的try/except方法可能更適合。

我可能會使用一個更通用的函數,可以給出類型來嘗試,但是:

def tryconvert(value, *types):
    for t in types:
        try:
            return t(value)
        except (ValueError, TypeError):
            continue
    return value

for line in infile:
    data = [tryconvert(x, int, float) for x in line.split()]

這會將轉換為整數的任何東西轉換為int ,但不會嘗試float ,最后它只是放棄並返回原始值,我們知道這將是一個字符串。 (如果我們不知道它是一個字符串,我們可以在調用tryconvert()結束str 。)

您可以使用方法str.isalpha(),str.isalphanum(),str.isdigit來確定您的字符串是否為數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM