【问题标题】:Replace decimal with comma in multiple text files在多个文本文件中用逗号替换十进制
【发布时间】:2018-11-21 10:45:58
【问题描述】:

我在一个文件夹中有 10 个 TAB 分隔的 txt 文件。它有三列(只有数字),前面有一个 21 行标题(文本和数字)。为了进一步处理它们,我想:

  1. 从所有文本文件中选择第二列(从第 21 行标题开始;我附上了带箭头的图),将逗号转换为十进制,并将 10 个文件中的每一列堆叠到一个新的制表符分隔/csv 文件中。所有文件一次。

我对脚本知之甚少。我有 Rstudio 和 Python,并试图摆弄一下。但我真的不知道该怎么办。由于我必须处理多个文件夹,如果可能的话,我的工作会非常简化。

Reference figure

【问题讨论】:

  • 所以你只需要抓住那一列并连接它,用逗号替换?你可以扔掉标题和其他列,你的输出应该是一个只包含一列的大文件?

标签: python r


【解决方案1】:

根据您的要求,听起来这个 Python 代码应该可以解决问题:

import os
import glob

DIR = "path/to/your/directory"
OUTPUT_FILE = "path/to/your/output.csv"
HEADER_SIZE = 21

input_files = glob.glob(os.path.join(DIR, "*.txt"))

for input_file in input_files:
    print("Now processing", input_file)

    # read the file
    with open(input_file, "r") as h:
        contents = h.readlines()

    # drop header
    contents = contents[HEADER_SIZE:]

    # grab the 2nd column
    column = []
    for row in contents:
        # stop at the footer
        if "####" in row:
            break

        split = row.split("\t")

        if len(split) >= 2:
            column.append(split[1])

    # replace the comma
    column_replaced = [row.replace(",", ".") for row in column]

    # append to the output file
    with open(OUTPUT_FILE, "a") as h:
        h.write("\n".join(column_replaced))
        h.write("\n")  # end on a newline

请注意,这将丢弃不属于输出文件第二列的所有内容。

【讨论】:

  • 谢谢约翰!我可以直接在 Python 中使用这个脚本吗?还是我需要一些库?
  • @AdityaIyer 不,没有依赖关系。只需调整路径。 os 库是 Python 内置的。
  • 我试过了,没有反应。脚本不应该有类似 create csv 之类的东西吗? imgur.com/a/iUTeJy5
  • 脚本假定目录中的所有内容都是输入文件,但我认为并非如此。我会进行编辑。但无论如何,您应该已经看到了输出。你用什么命令来运行它?
  • @AdityaIyer 已编辑。您是否看到正在打印任何输出?
【解决方案2】:

下面的代码不是一个精确的解决方案,但如果您按照它的思路进行操作,您将接近您所需要的。

output <- "NewFileName.txt"

old_dir <- setwd("your/folder")
files <- list.files("\\.txt")
df_list <- lapply(files, read.table, skip = 21, sep = "\t")
x <- lapply(df_list, '[[', 2)
x <- gsub(",", ".", unlist(x))
write.table(x, output, row.names = FALSE, col.names = FALSE)
setwd(old_dir)

【讨论】:

    【解决方案3】:
    list =[]
    filename = "my_text"
    file = open(filename, "r")
    for line in file:
        res=line.replace(",", ".")
        list.append(res)
        print(res)
    
    f = open(filename, "w")
    for item in list:
        f.write(item)`enter code here`
    

    【讨论】:

    • 这只会处理单个文件,而不是整个目录。它不会跳过标题。它不会将分隔文件写回磁盘。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2015-09-20
    • 2010-11-19
    • 2019-07-28
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多