【问题标题】:How to save data from a file but not in a variable or list in Python?如何从文件中保存数据,但不在 Python 中的变量或列表中?
【发布时间】:2018-07-09 09:48:19
【问题描述】:

我需要读取一个大约 5 GB 的文件,并在 Python 中编写一个与此相关的脚本:

cat file | awk -F '","'  '{if ($12 !="" ) print  $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100

9,10,12 是我想要从该文件中获取的参数。

我可以在 Bash 中毫无问题地做到这一点,也可以在带有 os.system 和该命令的 Python 脚本中做到这一点……但我需要正确编写 Python 脚本。

问题是我无法将数据保存在任何列表或变量中,因为要在服务器上运行的脚本由于文件大小而无法使用如此多的 RAM。

我正在考虑将数据写入文件而不是列表,但我还没有找到方法。

【问题讨论】:

  • 如果您不能使用太多内存,请使用中间文件。这将需要更长的时间,但它会起作用。为什么你没有做到这一点?哪个是问题?向我们展示您尝试过的代码,以便我们查明问题。

标签: python linux bash shell unix


【解决方案1】:

你至少可以使用一个 python Counter 变量

这可以优化三元组的存储和它们出现的次数。

伪脚本:

for line in file.readlines():
    data = line.strip().split(',')
    x = data[colums_that_you_want]
    xtoken = '_'.join(x)
    counter[xtoken] += 1


counter.most_common(100)

【讨论】:

    【解决方案2】:

    我不确定这是否是您要查找的内容,但如果您将其与其他用户建议的文本划分相结合,也许会有所帮助。

    您可以将数据保存在 .txt 文件中,如下所示:

    file = open("path/file.txt", "w") # This will create the file.
    write = file.write(text_variable) # This will write the content of text_variable into your file.txt
    file.close()
    

    还有另一种方式,就是使用 JSON:

    import json
    text = json.dumps(text_variable) # This will store the content of text_variable in a json format.
    file = open("path/file.json", "w") # This will create the json file.
    write = file.write(text) # This will write the content of text into your file.json
    file.close()
    

    然后,如果您想获取 JSON 的数据,只需执行以下操作:

    import json
    file = open("path/file.json", "r") # This will open the json file in read mode.
    jsontext = file.read()
    text = json.loads(jsontext) # You will have in text the original data you had at the beginning.
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      仅出于教育目的,我想证明这一行可以以更有效的方式重写:

      原文:

      $ cat file | awk -F '","'  '{if ($12 !="" ) print  $9,$10,$12}'| sort -n | uniq -c | sort -nr | head -100
      

      1.删除cat:

      cat 命令几乎不是每个人都需要的。

      $ awk -F '","' '{if ($12 !="" ) print  $9,$10,$12}' file | sort -n | uniq -c | sort -nr | head -100
      

      2。改进awk:

      $ awk -F '","' '($12 !="" ){print $9,$10,$12}' file | sort -n | uniq -c | sort -nr | head -100
      

      3。消除sort -n | uniq -c:你可以通过再次使用awk来摆脱这两个。您将所有内容存储在一个数组中,但这实际上正是 sortuniq 所做的。

      $ awk -F '","' '($12 !="" ){a[$9 OFS $10 OFS $12]++}
                      END{for(i in a) print a[i],i}' file | sort -nr | head -100
      

      4.消除最后两个管道: 使用 GNU awk,您可以使用 PROCINFO 对数组进行数字排序

      $ awk -F '","' 'BEGIN{PROCINFO["sorted_in"] = "@val_num_desc"}
                      ($12 !="" ){a[$9 OFS $10 OFS $12]++}
                      END{for(i in a) {j++; print a[i],i; if (j==100) exit} }' file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        • 2020-11-22
        • 2015-09-01
        • 2017-04-14
        • 1970-01-01
        相关资源
        最近更新 更多