【问题标题】:Add each character from each line of a text file, to a list in Python将文本文件每一行中的每个字符添加到 Python 中的列表中
【发布时间】:2017-03-29 12:45:24
【问题描述】:

所以我想读取文本文件每一行的每个字符(用空格分隔),并将它们添加到每行列表的单独索引中。

file = open("theTextFile.txt", 'r+')
pal = []

words = file.split(' ')
pal.append(words)

print(pal)
split_line(file)

文本文件的每一行都有一个由空格分隔的字符。 编辑器不允许我在文本文件中使用标点符号,但下面是它的外观示例。

r o t o r

r a c e c

【问题讨论】:

  • This 会有所帮助。
  • 你能给出输入和预期输出的简短例子吗?
  • 这里有很多关于如何在 Python 中读取文件并将其输出到 hereherehere 之类的列表中的帖子,您应该能够理解这一点出去。但是你的问题不清楚,你需要举一个“theTextFile.txt”的例子,告诉我们你的预期输出是什么。

标签: python arrays


【解决方案1】:

也许你想要这样?

words = []
with open('theTextFile.txt', 'r') as fp:
    words = sum([l.strip().split(' ') for l in fp], [])
print(words)

【讨论】:

    【解决方案2】:

    这是我为解决我的问题所做的:

    lines = open('theTextFile.txt','r')
    
    secondList = []
    for line in lines:
        line = line.split()
        secondList.append(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多