【问题标题】:extract data using python使用python提取数据
【发布时间】:2021-06-24 12:31:16
【问题描述】:

我有一个文本文件 (abc.txt),其中包含以下内容:

10 20 0 #1st line
-9 -9 -9 -9 #2nd line
4 4 #3rd line
2 2 0. 0. hello #4th line
15 25 1 #5th line
-9 -9 0 1 #6th line
5 5 #7th line
7 7 8. 8. hello #8th line

我想获取 "hello" 单词之前的所有数据并将其保存在 csv 文件中。这意味着根据上述数据将有两行:

Ist row: 10 20 0 -9 -9 -9 -9 4 4 1 1 2 2
2nd row: 15 25 1 -9 -9 0 1 5 5 7 7 8 8

到目前为止,我尝试了 jpg 文件中的附加代码(当然它只会给出一个空的 csv 文件)

with open(inputDir + "all_data.csv", "w") as output1File:
output = "";

inputFile = inputDir + fileName;

with open(inputFile, "r") as inputFile:
    for line in inputFile:              
        if line.endswith(" name"):
            values = line.split(" ")
            value = values[1].strip();
            output = output + value + "\n" ;
output1File.write(output + "\n");

谁能帮助我如何编写这段代码,以便我可以得到上面提到的两行的 all_data.csv 文件?我在文本文件中显示的数据集只是一个案例研究。我的原始文件包含大量数据但模式相同。

提前致谢:)

python code that I wrote so far

abc.txt file

附:我是 Python 新手。刚开始学习。

【问题讨论】:

  • 谢谢。抱歉,这是我在 stackoverflow 中的第一篇文章。我又试了一次,看起来代码现在是 TEXT 了。

标签: python csv split txt


【解决方案1】:

只使用正则表达式怎么样?

import re

with open('abc.txt', 'r') as f:
    text = f.read()

text = re.sub(r'\s+', ' ', text) # whitespaces (including newline) → ' '
text = re.sub(r' hello ', '\n', text) # hello → newline

with open('output.txt', 'w') as f:
    f.write(text)

以下代码可能更类似于您的原始代码:

output = ''

with open("abc.txt", "r") as f:
    temp = []
    for line in f:
        values = line.split()
        if values: # if the line is empty, then pass
            if values[-1] == 'hello': # if last value is 'hello'
                output += ' '.join(temp + values[:-1]) + '\n'
                temp = []
            else:
                temp += values # store this line

with open("output.txt", "w") as f:
    f.write(output);

在您的原始代码中需要注意的一点是line.endswith(" name") 不起作用。当您使用for line in inputFile: 遍历文件时,变量line 实际上是一个类似'... name\n' 的字符串,即它以name\n 结尾,而不是name。所以你需要使用line.endswith(" name\n")

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2022-11-21
    • 2020-03-19
    • 2016-04-03
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    相关资源
    最近更新 更多