【问题标题】:how do i find and replace items in a text file in pyscripter? [closed]如何在 pyscripter 的文本文件中查找和替换项目? [关闭]
【发布时间】:2013-09-30 12:00:36
【问题描述】:

如何在 pyscripter 中查找和替换文本文件中的项目?

在脚本中,我通过将列表转换为字符串将其放入文本文件中。现在它有方括号。我需要删除这些,以便取出单个单词和数字。我需要一个脚本,它可以让我找到这些括号并将其替换为“无”。

请帮忙!

这是我的文本文件当前的样子。 1

【问题讨论】:

  • 你可以在你的问题中粘贴小sn-ps,或者使用dpaste.compastebin.com等;纯文本的屏幕截图不太符合人体工程学。

标签: python serialization replace find pyscripter


【解决方案1】:

首先,当您需要将列表存储在文件中时,请使用 JSON、pickle 或等效项。 JSON 更适合用于长期存储以及旨在由其他程序读取或通过网络发送的存储:

import json

my_list = ["hello", "world"]

with open('file.txt', 'w') as f:
    json.dump(my_list, f)

或者,如果您只想以纯文本格式每行存储一个单词/句子/短语:

my_list = ["hello", "world"]
with open('file.txt', 'w') as f:
    f.write('\n'.join(my_list))  # assuming your list isn't large
    f.write('\n')

(另一方面,酸洗适用于临时/内部存储,以及存储无法转换为 JSON 可以处理的形式的内容;有关更多信息,请查找 pickle 模块的文档.)

现在,如果您搞砸了,只是将列表的字符串表示形式放入文件中,您可以手动清理它,或者使用以下帮助程序:

import ast
import json

with open('file.txt') as f:
    contents = f.read()
contents = ast.literal_eval(contents)  # parses the string as if it were a Pytnon literal (which it is)

with open('file.txt', 'w') as f:
    json.dump(contents, f)  # write back as JSON this time

如果您的文件包含多个列表,每个列表位于单独的行中,您可以使用:

import ast
import json

with open('file.txt') as f:
    lines = f.read().split('\n')
contents = [ast.literal_eval(line) for line in lines]

# ...and now choose from above how you'd like to write it back to the file

注意:哦,而且...这似乎与 pyscripter 无关,除非我错过了什么。

【讨论】:

  • 谢谢。我正在使用 pyscripter 制作一个可以存储配方并在以后访问的程序..(在 word 文件中)
  • 确实有道理,谢谢!唯一的问题是内容的行 = [ast.listeral_eval(line) for line in lines] 一旦程序到达这部分,就会出现错误。
  • 对不起;错字:应该是literal_eval 而不是listeral_eval;固定答案。
  • 这个答案对你有用吗?如果确实如此,请考虑接受或至少投票。
  • 对不起,伙计。谢谢你确实帮助我朝着正确的方向前进 :) 抱歉,从前几天就没有了。
猜你喜欢
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
  • 2020-07-29
  • 2013-10-07
相关资源
最近更新 更多