【问题标题】:Create a column from a CSV list in Python 3在 Python 3 中从 CSV 列表创建一列
【发布时间】:2014-08-15 18:46:54
【问题描述】:

我拥有的是一个 CSV 文件,其中标题是“关键字”,并且标题下的每个单元格都包含文本,因此它看起来像这样:

Keyword
Lions Tigers Bears
Dog Cat
Fish
Shark Guppie

我要做的是将该列表中的每个短语解析为单个单词,以便最终产品如下所示:

     Keyword
      Lion
      Tigers
      Bear
      Dog
      Cat...

现在,我的代码获取 CSV 文件并将列表拆分为单独的部分,但仍然没有创建统一的列。

datafile = open(b'C:\Users\j\Desktop\helloworld.csv', 'r')
data = []
for row in datafile:
   data.append(row.strip().split(","))
   white = row.split()
   print (white)

我的输出如下所示: ['关键词'] ['狮子','老虎'] ['海豚','熊','斑马'] ['狗','猫']

我知道可能的解决方案将涉及使用 lineterminator = '\n' 但我不确定如何将其合并到我的代码中。任何帮助将不胜感激!

** 已编辑 -- 源 CSV 没有逗号分隔每个短语中的单词

【问题讨论】:

  • 有多少列?
  • 在这个文件中,只有一个。不过,未来有可能还会有更多!
  • 您只想将所有内容写在一个列中?
  • 没错,所以关键字下的每个单元格都将包含一个单词,而不是像“狗、猫、熊”这样的短语
  • 你是写到同一个文件吗?

标签: python csv python-3.x


【解决方案1】:

在列表中使用extend 而不是append 将列表中的所有项目添加到另一个列表中:

datafile = open(b'C:\Users\j\Desktop\helloworld.csv', 'r')
data = []
for row in datafile:
   data.extend(row.strip().split())
print(data)

要消除各个条目周围的更多空白,请使用

datafile = open(b'C:\Users\j\Desktop\helloworld.csv', 'r')
data = []
for row in datafile:
   data.extend(item.strip() for item in row.split())
print(data)

另外,为了安全地读取文件,您可以使用with 语句(您不必再担心关闭文件):

with open('C:\Users\j\Desktop\helloworld.csv', 'r') as datafile:
    data = []
    for row in datafile:
       data.extend(item.strip() for item in row.split())
    print(data)

编辑:在 OP 澄清后,我删除了 split 中的 "," 参数,以便在空格而不是逗号上分割。

【讨论】:

    【解决方案2】:

    您应该能够使用此代码来读取您的文件。用您拥有的文件名替换文件名。我的文件内容正是您在上面发布的内容。

    keyword = "Keyword"
    
    with open("testing.txt") as file:
        data = file.read().replace("\n", " ").split(" ")
        for item in data:
            if item == keyword:
                print("%s" % keyword)
            else:
                print(" %s" % item)
    

    输出:

    Keyword
     Lions
     Tigers
     Bears
     Dog
     Cat
     Fish
     Shark
     Guppie
    Keyword
     Dog
     Something
     Else
     Entirely
    

    【讨论】:

      【解决方案3】:

      你只需要拆分读取:

      with open("in.txt","r+") as f:
          data = f.read().split()
          f.seek(0) # go back to start of file
          f.write("\n".join(data)) # write new data to file
      ['Keyword', 'Lions', 'Tigers,', 'Bears', 'Dog', 'Cat', 'Fish', 'Shark', 'Guppie']
      

      【讨论】:

        猜你喜欢
        • 2020-11-02
        • 2013-08-15
        • 2018-09-30
        • 1970-01-01
        • 2012-09-18
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        相关资源
        最近更新 更多