【问题标题】:How to a grab an array from a text file with array written in it?如何从写入数组的文本文件中获取数组?
【发布时间】:2020-05-27 20:14:22
【问题描述】:

下面是我的代码。我正在尝试创建一个文本文件,允许您编辑程序中使用的关键字。

words = ['bob', 'jones', 'billy', 'josh']

try:
    with open('./keywords.txt', "x", encoding="utf-8") as g:
        g.write(str(words) + '\n\n' + 'EDIT THE KEYWORDS BY ADDING OR REMOVING THE TEXT\n' + 'Make sure to add use the current format in order for it to work')
except FileExistsError:
    print('Reading keywords')
    keywords = open('./keywords.txt' , "r", encoding="utf-8")
    words = keywords.readline(1)
    print(words)

当我使用这段代码时,得到的只是 -

[

【问题讨论】:

  • 你的预期输出是什么?

标签: python arrays text


【解决方案1】:

您可以使用 ast.literal_eval() 。将readline(1) 替换为readline()。这是代码。

words = ['bob', 'jones', 'billy', 'josh']
import ast
try:
    with open('./keywords.txt', "x", encoding="utf-8") as g:
        g.write(str(words) + '\n\n' + 'EDIT THE KEYWORDS BY ADDING OR REMOVING THE TEXT\n' + 'Make sure to add use the current format in order for it to work')
except FileExistsError:
    print('Reading keywords')
    keywords = open('./keywords.txt' , "r", encoding="utf-8")
    words = keywords.readline()
    listobj = ast.literal_eval(words)
    print(listobj)
    print(listobj[2])

打印

['bob', 'jones', 'billy', 'josh']
billy

【讨论】:

  • 有同样的问题,它将单词分成字母作为另一个答案。
  • 每个单词都是由字母组成的,所以它会把它拆分成字母。你到底想要什么?在这段代码中,所有单词都存储在一个列表中
【解决方案2】:

这是第一次运行程序后你的文本文件的样子:

['bob', 'jones', 'billy', 'josh']

EDIT THE KEYWORDS BY ADDING OR REMOVING THE TEXT
Make sure to add use the current format in order for it to work

使用words = keywords.readline(1) 仅从行中读取 1 个字节的数据。您可以使用以下任一行来返回整行:

keywords.readline()
keywords.readline(-1)

完整代码:

words = ['bob', 'jones', 'billy', 'josh']

try:
    with open('./keywords.txt', "x", encoding="utf-8") as g:
        g.write(str(words) + '\n\n' + 'EDIT THE KEYWORDS BY ADDING OR REMOVING THE TEXT\n' + 'Make sure to add use the current format in order for it to work')
except FileExistsError:
    print('Reading keywords')
    with open('./keywords.txt' , "r", encoding="utf-8") as myFile:
        file = []
        for line in myFile:
            file.append(line)
        words = file[0]
        print(words)

输出:

Reading keywords
['bob', 'jones', 'billy', 'josh']

>>>

【讨论】:

  • 那种工作,如果我这样做,那么它不会把它变成数组形式,而是在我想要的时候将它打印为像“b”“i”这样的单独字母是“比利”,因为它是关键字。
  • 这就是你的全部程序吗? @NoobierNoob 我编辑了我的答案以反映我使用的全部内容并显示输出。
  • 它似乎仍然将他们视为个体。 1 ' https://....com 1 b https://....com 1 o https://....com 1 b https://....com 1 ' https://....com 1 , https://....com 1 https://....com 1 ' https://....com 1 j https://....com哪里是“b”或“o”,我想让它说出整个单词
  • 我尝试对代码进行另一次编辑,这次循环遍历文件并存储第一行。它仍然给我正确的输出,我不确定为什么你的输出不同。是什么导致输出中的 URL 格式?我想知道错误是否在程序的不同部分。似乎你在某个地方循环遍历列表并且只抓取第一个字母。
猜你喜欢
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2011-04-10
相关资源
最近更新 更多