說我有此格式的文本文件:如何讀取文本文件到單獨列出蟒蛇
100 20個鶯飛
,我想讀INT(S)到自己的列表和字符串放入它自己的列表中......我將如何在python中進行此操作。我試過
data.append(map(int, line.split()))
沒有工作......任何幫助?
說我有此格式的文本文件:如何讀取文本文件到單獨列出蟒蛇
100 20個鶯飛
,我想讀INT(S)到自己的列表和字符串放入它自己的列表中......我將如何在python中進行此操作。我試過
data.append(map(int, line.split()))
沒有工作......任何幫助?
從本質上講,我讀通過行的文件行,分裂他們。我首先檢查是否可以將它們變成一個整數,如果我失敗了,將它們視爲字符串。
def separate(filename):
all_integers = []
all_strings = []
with open(filename) as myfile:
for line in myfile:
for item in line.split(' '):
try:
# Try converting the item to an integer
value = int(item, 10)
all_integers.append(value)
except ValueError:
# if it fails, it's a string.
all_strings.append(item)
return all_integers, all_strings
然後,給定文件( 'mytext.txt')
100 20 the birds are flying
200 3 banana
hello 4
...做在命令行下返回...
>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']
+1。這種使用例外是**完美**。刪除「我不開心......」的業務。這很好。 –
是的,我在某處讀到異常應該只用於特殊行爲,在這裏並不是這樣。我刪除它。 – Michael0x2a
+1耶!這裏的例外是正確的。 – juliomalegria
pop
從列表中刪除元素並返回它:
words = line.split()
first = int(words.pop(0))
second = int(words.pop(0))
當然,這是假設你的格式始終int int word word word ...
。
再加入字符串的其餘部分:
words = ' '.join(words)
而且在Python 3,你甚至可以這樣做:
first, second, *words = line.split()
這是非常整潔。雖然您仍然必須將first
和second
轉換爲int
's。
如果我理解正確你的問題:
import re
def splitList(list):
ints = []
words = []
for item in list:
if re.match('^\d+$', item):
ints.append(int(item))
else:
words.append(item)
return ints, words
intList, wordList = splitList(line.split())
會給你兩個列表:[100, 20]
和['the', 'birds', 'are', 'flying']
這裏有一個簡單解。請注意,對於非常大的文件,其效率可能不如其他文件高,因爲它對line
每次迭代word
兩次。
words = line.split()
intList = [int(x) for x in words if x.isdigit()]
strList = [x for x in words if not x.isdigit()]
'map(int,line.split())'將'int'應用於* entire *行。是什麼讓你認爲這會將數字和單詞分開? –