[英]Python 2 - How do I import a text file containing a long sequence of digits and convert it to a string of individual numbers?
I want to take a text file that is a long sequence of digits with line breaks, ie something like 我想获取一个文本文件,该文件是带有换行符的长数字序列,即类似
38482406847387
85869153438194
96531040384827
43157689643163
but much larger, and convert it to a string that would just read 但更大,然后将其转换为一个将读取的字符串
[3,8,4,8,...,1,6,3]
so that I can iterate over it, manipulate it, visualise it and so on. 这样我就可以对其进行迭代,操作,可视化等等。
I have had a look at the open()
function but so far I can only get it to break up the file into separate lines. 我看过
open()
函数,但到目前为止,我只能将它分解成单独的行。 I know I can use a for
loop to go through the giant string of the whole document and form a list that way, but then I get '/n' and spaces showing up everywhere, which is undesirable. 我知道我可以使用
for
循环遍历整个文档的巨型字符串并以这种方式形成列表,但是随后我会在所有地方都显示'/ n'和空格,这是不希望的。
For context, I grabbed a text file from the web of some preposterous number of digits of pi, and I thought it would be instructive and interesting to go through it and look for patterns, plot the distribution of digits, convert to ASCII and other such nonsense. 作为上下文,我从网上获取了一个文本文件,其中包含一些荒谬的pi数字,我认为遍历它并寻找模式,绘制数字分布,转换为ASCII等将是很有启发性和有趣的。废话。 I figured it would be a fun way for me to learn a bit more about Python.
我认为这对我来说是更多了解Python的有趣方式。
import re
print re.findall('\d', open('file.txt', 'r').read())
For small files: 对于小文件:
with open('path/to/file') as infile:
answer = list(int(i) for i in ''.join(line.strip() for line in infile))
For larger files: 对于较大的文件:
answer = []
with open('path/to/file') as infile:
for line in infile:
answer.extend([int(i) for i in line.strip()])
If you get all the numbers as a string then you can use 如果您将所有数字作为字符串获取,则可以使用
# 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()]
This is shorter. 这比较短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.