【问题标题】:I want to put my text file into an array word by word instead of line by line我想将我的文本文件逐字而不是逐行放入数组中
【发布时间】:2019-06-07 12:52:03
【问题描述】:

我正在处理每个单词具有不同统计信息的大数据文件。我想通过 stat 将这些单词分成它们自己的数组。

我用过readline(),但那太长了。我的文件中的数据是段落形式的,并不是每一行都缩进。

for i in range(1, 169):
    date.append(filename.readline().rstrip(','))
    num_of_games.append(filename.readline().rstrip(','))
    day_of_week.append(filename.readline().rstrip(','))
    vteam_league.append(filename.readline().rstrip(','))

date = [20180405,20180406, 20180407, 20180408]
num_of_games = [1, 1, 1, 2, 3, 2, 1, 2] 

【问题讨论】:

  • 你能举一个数据文件的简短例子吗?

标签: python list text-files


【解决方案1】:

这看起来像一个逗号分隔的文件。使用Python CSV 库读取文件。类似的东西

import csv

num_of_games = []
date = []
day_of_week = []
vteam_league = []
with open(filename) as csvfile:
     reader = csv.reader(csvfile)
     for row in reader:
         date.append(row[0])
         num_of_games.append(row[1])
         day_of_week.append(row[2])
         vteam_league.append(row[3])

【讨论】:

  • 在执行此操作之前,我是否需要将 date、num_of_games 等声明为列表?
  • 是的,我在上面添加了
猜你喜欢
  • 1970-01-01
  • 2013-12-17
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多