我有一個包含數千行的大型文本檔案,但一個涵蓋相同想法的簡短示例是:
vapor dust -2C pb
x14 71 hello! 42.42
100,000 lover baby: -2
有整數、字母數字和浮點數的混合。
嘗試 SOLN。我這樣做是為了創建一個由字串組成的單個串列,但是我無法根據每個單元格的數字或字母數字來隔離每個單元格
with open ('file.txt','r') as f:
data = f.read().split()
#dirty = [ x for x in data if x.isnumeric()]
print(data)
線路#dirty失敗。
我很幸運地使用以下代碼構建了一個包含幾乎所有必需值的串列:
with open ('benzene_SDS.txt','r') as f:
for word in f:
data= word.split()
clean = [ x for x in data if x.isnumeric()]
res = list(set(data).difference(clean))
print(clean)
但它不回傳單個串列,它是一個串列串列,其中大部分是空白 []。
給出了一個提示,使用“try”控制陳述句對解決問題很有用,但我不知道如何使用它。
任何幫助將不勝感激!謝謝。
uj5u.com熱心網友回復:
如果您主要詢問如何使用try來檢查有效性,這就是您所追求的:
values = []
with open ('benzene_SDS.txt','r') as f:
for word in f.read().split():
try:
values.append(float(word))
except ValueError:
pass
print(values)
輸出:
[71.0, 42.42, -2.0]
但是,并不是說這不會決議'100,000'為100or 100000。
這段代碼會這樣做:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
values = []
with open('benzene_SDS.txt', 'r') as f:
for word in f.read().split():
try:
values.append(locale.atof(word))
except ValueError:
pass
print(values)
結果:
[71.0, 42.42, 100000.0, -2.0]
請注意,使用以下代碼運行相同的代碼:
locale.setlocale(locale.LC_ALL, 'nl_NL.UTF-8')
產生不同的結果:
[71.0, 4242.0, 100.0, -2.0]
由于荷蘭,用作小數分隔符和.千位分隔符(基本上只是在 42.42 中被忽略)
uj5u.com熱心網友回復:
numbers = []
with open('file.txt','r') as f:
for line in f.read():
words = line.split()
numbers.extend([word for word in words if word.isnumeric()])
# Print all numbers
print(numbers)
# Print all unique numbers
print(set(numbers))
# Print all unique numbers, converted to floats
print([float(n) for n in set(numbers)])
如果你特別需要一個串列,那么你可以用list().
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/413830.html
標籤:
