簡體   English   中英

Python 2-如何導入包含一長串數字的文本文件並將其轉換為單個數字字符串?

[英]Python 2 - How do I import a text file containing a long sequence of digits and convert it to a string of individual numbers?

我想獲取一個文本文件,該文件是帶有換行符的長數字序列,即類似

38482406847387
85869153438194
96531040384827
43157689643163

但更大,然后將其轉換為一個將讀取的字符串

[3,8,4,8,...,1,6,3]

這樣我就可以對其進行迭代,操作,可視化等等。

我看過open()函數,但到目前為止,我只能將它分解成單獨的行。 我知道我可以使用for循環遍歷整個文檔的巨型字符串並以這種方式形成列表,但是隨后我會在所有地方都顯示'/ n'和空格,這是不希望的。

作為上下文,我從網上獲取了一個文本文件,其中包含一些荒謬的pi數字,我認為遍歷它並尋找模式,繪制數字分布,轉換為ASCII等將是很有啟發性和有趣的。廢話。 我認為這對我來說是更多了解Python的有趣方式。

import re

print re.findall('\d', open('file.txt', 'r').read())

對於小文件:

with open('path/to/file') as infile:
    answer = list(int(i) for i in ''.join(line.strip() for line in infile))

對於較大的文件:

answer = []
with open('path/to/file') as infile:
    for line in infile:
        answer.extend([int(i) for i in line.strip()])

如果您將所有數字作為字符串獲取,則可以使用

# here, digits is the numbers as a string including the \n character
list = [digit for digit in digits.replace('\n', '')]
with open("/path/to/file") as f:
    print [int(x) for x in f.read() if x.isdigit()]

這比較短。

暫無
暫無

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

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