从.txt文件提取值到.xlsx

发布于 2025-01-25 06:44:53 字数 868 浏览 1 评论 0原文

我需要从文本文件中提取特定值,其中包括

垃圾邮件:1;鸡蛋:(2,3,4) 垃圾邮件:5;鸡蛋:(6,7,8)

我需要将它们放入Excel文件中的单独列中。我不知道我是否应该使用RE,是否有一种更简单的方法?


更新:我从以下代码开始:

import pandas as pd
import os

f_path = "C:/path"

f_input = os.path.join(f_path, 'log.txt')
f_output = os.path.join(f_path, 'log.csv')

df = pd.read_csv(f_input, sep='\t')
df.to_csv(f_output, index=False)

现在我在.csv文件中有此输出,但是,我希望它看起来像:

Sheet1:

spam
1
5

Sheet2:

Eggs
2
3
4
6
7
8

8取得这样的结果?

I need to extract specific values ​​from a text file with content like

spam: 1; eggs: (2, 3, 4)
spam: 5; eggs: (6, 7, 8)

And I need to put them into separate columns in an excel file. I don't know if I should use re for this, is there perhaps an easier way of doing it?


Updated: I've started with the following code:

import pandas as pd
import os

f_path = "C:/path"

f_input = os.path.join(f_path, 'log.txt')
f_output = os.path.join(f_path, 'log.csv')

df = pd.read_csv(f_input, sep='\t')
df.to_csv(f_output, index=False)

Now I have this output in a .csv file, however, I would like it to look like this:

Sheet1:

spam
1
5

Sheet2:

eggs
2
3
4
6
7
8

How can I attain such a result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

各空 2025-02-01 06:44:53

为什么要呢?您只需读取文本文件的行,然后使用下面的此脚本将其写入CSV

def extract_values_from_text_file(text_file_path, csv_file_path):
    with open(text_file_path, "r") as f:
        lines = f.readlines()
        with open(csv_file_path, "w") as f:
            for line in lines:
                line = line.replace(":", ",")
                f.write(line)

why re? you can simply read lines from text file and write them to a csv using this script below

def extract_values_from_text_file(text_file_path, csv_file_path):
    with open(text_file_path, "r") as f:
        lines = f.readlines()
        with open(csv_file_path, "w") as f:
            for line in lines:
                line = line.replace(":", ",")
                f.write(line)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文