CSV文件提取

xggvc2p6  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(168)

我正在努力解决这个问题。
我有一个csv文件,看起来像这样:

Elias,"Elias won 0.0% of all there games!
[37mThere score: 0  |  Robots Score: 1"

我试图将数字“0”和“1”导入到一个变量中,但这些数字总是在变化,所以我想要某种代码,可以抓住它的值,无论它是什么。
例如,如果文件如下所示:

Andrew,"Andrew won 13.5% of all there games!
[37mThere score: 6  |  Robots Score: 17"

我需要提取6和17
Im导入到python中
我试过

import csv

# Open the CSV file
with open('your_file.csv', newline='') as csvfile:
    # Create a CSV reader object
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')

    # Loop through each row of the CSV file
    for row in reader:
        # Extract the number from the row
        number = row[0].split(': ')[-1].split()[0]
        # Convert the number to a float (if desired)
        number = float(number)
        # Print the number to verify it was extracted correctly
        print(number)

然而,这给了我错误的输出

a64a0gku

a64a0gku1#

您必须:

  • 第一次按|拆分
  • :拆分
  • 获取最后元素
  • 删除空格
  • 转换为int
import csv

with open('your_file.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')

    for row in reader:
        numbers =[int(scores.split(":")[-1].strip()) for scores in row[1].split("|")]
        print(f"{numbers=}") # This is gonna print: numbers=[6, 17]

边注:

备选办法2
对于这类操作(一个接一个地堆叠),有时使用生成器表达式将其拆分为特定的步骤是很方便的。它们是惰性计算的,所以无论你处理多大的文件,你都不会耗尽内存,你可以看到每个特定的步骤作为一行,这更容易分析(而不是一个长长的列表解析)。

import csv

with open('your_file.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')

    for row in reader:
        numbers = (scores.split(":") for scores in row[1].split("|"))
        numbers = (scores[-1] for scores in numbers)
        numbers = (scores.strip() for scores in numbers)
        numbers = (int(scores) for scores in numbers)
        # The you can loop through the numbers
        for n in numbers:
            print(f"{n=}") # This is gonna print: n=6 in the 1st iteration and n=17 in the 2nd

相关问题