【问题标题】:Python: Iterate over every row of a CSV, count the tokens in every row, create a new CSV with the number of tokens for each row of the original CSVPython:遍历 CSV 的每一行,计算每一行中的标记,创建一个新的 CSV,其中包含原始 CSV 每一行的标记数
【发布时间】:2018-06-24 13:44:20
【问题描述】:

)

我有一个如下所示的 CSV 文件:

块引用

  • 身份证内容
  • 文本 1 这里有一些文本
  • Text 2 她也来了一些文字
  • 文本 3 依此类推……

块引用

我想编写一个代码来迭代这个 CSV 表的每一行。 然后计算每行中的标记数(例如每个文本) 然后创建一个新的 CSV-Table 作为输出,其中应该只有 Text-ID 和此文本中的 Token 数量。

块引用

输出 CSV 文件应如下所示:

  • ID NumberOfTokens
  • 文字 1 8
  • 文本 2 12
  • 文本 3 15

块引用

到目前为止,我有这个代码:

import csv
from textblob_de import TextBlobDE as TextBlob

data = open('myInputFile.csv', encoding="utf-8").readlines()

blob = TextBlob(str(data))


csv_file = open('myOutputFile.csv', 'w', encoding="utf-8")
csv_writer = csv.writer(csv_file)
# Define the Headers of the CSV
csv_writer.writerow(['Text-ID', 'Tokens])


def numOfWordTokens(document):

    myList = []

    for eachRow in document:
        myList.append(eachRow)
        return "\n".join(myList)

        #return eachRow
        #print(eachRow)

        # Count Tokens
        #countTokens = len(wordTokens2.split()) # Output: integer
        #return countTokens
        #myList.append(str(countTokens))


wordTokens = numOfWordTokens(data)

# Write Content in the CSV-Table Rows
csv_writer.writerow([wordTokens])
csv_file.close()

那么,首先我有以下问题?

当我返回 eachRow 时,我在 Shell 中没有得到任何输出,并且只有 1. 行作为新创建的 CSV 文件中的输出。 当我打印 (eachRow) 时,我实际上将每一行打印为 Shell 中的输出,但我新创建的 CSV 文件只是空的!

所以这是我遇到问题的第一部分,所以我不能继续转到我实际计算每一行中的标记并将标记的数量写入新的 CSV 文件的部分。

【问题讨论】:

  • 只是给出一个输入 csv 和输出 csv 的具体例子,很难知道你的目标是什么
  • 我在问题中写了我的输入和输出 CSV 是什么。很抱歉,它看起来不太漂亮,因为我不知道如何在 stackoverflow 上写一个表格。所以在我的问题中,这两个 CSV 看起来像一个列表,对此我很抱歉。我将在这里再次尝试解释:。输入 CSV 包含带有文本的行。在这里,我想计算令牌并将带有令牌数量的输出 CSV 行作为输出。

标签: python loops csv


【解决方案1】:

使用 pandas 非常简单,但如果您不想使用其他模块,那也可以 :) 我已经为 pandas 和手动迭代数据添加了代码:

import pandas as pd
import csv


def main_pandas(path_to_csv: str, target_path: str):
    df = pd.read_csv(path_to_csv, encoding='utf-8')
    df['tokens'] = df['Content'].apply(lambda x: len(x.split()))
    sub_df = df[['ID', 'tokens']]
    sub_df.to_csv(target_path, index=False)


def main_manual(path_to_csv: str, target_path: str):
    with open(path_to_csv, 'r') as r_fp:
        csv_reader = csv.reader(r_fp)
        next(csv_reader)  # Skip headers
        with open(target_path, 'w') as w_fp:
            csv_writer = csv.writer(w_fp)
            csv_writer.writerow(['Text ID', 'tokens'])  # Write headers
            for line in csv_reader:
                text_id, text_content = line
                csv_writer.writerow([text_id, len(text_content.split())])


if __name__ == '__main__':
    main_manual('text.csv', 'tokens.csv')

【讨论】:

  • 非常感谢!我尝试了 main_manual-function 并且它有效! :-) 你帮了我很多!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2019-04-04
  • 2018-10-17
相关资源
最近更新 更多