简体   繁体   English

Python-从txt创建数组

[英]Python-Create array from txt

I'm trying to create an array of stock tickers in Python 2.7 from a txt file.我正在尝试从 txt 文件在 Python 2.7 中创建一个股票行情数组。 The txt file simply has 1 ticker per line like: txt 文件每行只有 1 个代码,例如:

SRCE
ABTX
AMBC
ATAX

The code I'm using looks like:我正在使用的代码如下所示:

FinTick= []

    def parseRus():
        try:
        readFile=open(r'filename.txt','r').read()
        splitFile=readFile.split('\n')
        FinTick.append(splitFile)
        print FinTick



        except Exception, e:
        print str(e)

When I call 'parseRus()' I get an output that looks like:当我调用 'parseRus()' 时,我得到的输出如下所示:

'\xff\xfeS\x00R\x00C\x00E\x00\r\x00', '\x00A\x00B\x00T\x00X\x00\r\x00', '\x00A\x00M\x00B\x00C\x00\r\x00', '\x00A\x00T\x00A\x00X\x00\r\x00'

The correct letters are present but not printing in plane text.存在正确的字母,但未打印在平面文本中。 I've used a couple other logic methods to populate the array but still get the same output format.我使用了一些其他逻辑方法来填充数组,但仍然获得相同的输出格式。

>>> tickers = []
>>> with open("filename.txt", "r") as f:
        for ticker in f.readlines():
            tickers.append(ticker.strip())


>>> tickers
['SRCE', 'ABTX', 'AMBC', 'ATAX']

Try using readlines() and strip() instead.尝试使用readlines()strip()代替。

Edit: Some clarity around f.readlines() and strip() :编辑:关于f.readlines()strip()一些清晰度:

>>> with open("filename.txt", "r") as f:
        print(f.readlines())

['SRCE\n', 'ABTX\n', 'AMBC\n', 'ATAX']

So, when we're iterating through the list object returned by f.readlines() , we will need to strip the newline \\n characters.因此,当我们遍历f.readlines()返回的list对象时,我们需要f.readlines()换行符\\n字符。 Use the strip() method for str types to do this.使用str类型的strip()方法来执行此操作。

Edit 2: @Eli is right.编辑 2:@Eli 是对的。 We can just use for ticker in f instead of for ticker in f.readlines() , too.我们也可以for ticker in f.readlines()使用for ticker in f而不是for ticker in f.readlines()

>>> tickers = []
>>> with open("filename.txt", "r") as f:
        for ticker in f:
            tickers.append(ticker.strip())

>>> tickers
['SRCE', 'ABTX', 'AMBC', 'ATAX']

I finally figured a fix.我终于想到了解决办法。

I had to modify the text file from 1 column to 1 row then saved as a .csv and modified the code to:我不得不将文本文件从 1 列修改为 1 行,然后另存为 .csv 并将代码修改为:

FinTick= []

def parseRus():
    try:
        readFile=open(r'filename.csv','r').read()
        splitFile=readFile.split(',')
        for eachLine in splitFile:
            splitLine=eachLine.split(',')
            ticker=splitLine[0]
            FinTick.append(ticker.strip())



    except Exception, e:
    print str(e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM