【问题标题】:Modifying text documents with python用python修改文本文档
【发布时间】:2011-10-04 01:14:13
【问题描述】:

假设我有一个 .txt 文档,其中包含 1,000 个名称。 文档如下所示:

乔恩 简 乔 杰克 杰里米

等等。

现在,假设我想附加“is lame”。到每个名字。 所以,我希望列表看起来像这样:

乔恩很瘸。 简是瘸腿的。 乔是瘸腿的。 杰克是瘸腿的。 杰里米是瘸腿的。

等等。

我将如何从命令行使用 python 执行此操作?

【问题讨论】:

  • 到目前为止您尝试过什么?如果您在自己的第一次尝试中表现出一些努力,那么您将学到比在这里获得答案更多的东西。尝试一下并在您的问题中发布一些代码。

标签: python file text append


【解决方案1】:

这并不完全是 python 特定的,但你明白了....

In a loop parsing each token (name):
1.  Get the name into a string
2.  Append "is lame" or whatever else to the string
3.  Append that string onto a buffer

循环结束后,用新缓冲区替换您的文档。

【讨论】:

  • 对不起,我应该更具体。我可以执行代码的实际附加部分,“名称中的名称”等。我的意思是,如何在文本文档中实际导入原始名称,以便我可以修改它们。我需要使用导入功能吗?
  • 对不起,对python了解不多。我相信你可以用谷歌在 python 文件 i/o 上找到一些东西
【解决方案2】:

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

简而言之:

f = open('my_names_file.txt')
data = f.read()
f.close()
output = ""
for name in data.split(' '):       # This assumes each name is separated 
    output += name + " is lame. "  # by a space and no name contains a space
print output

将输出写回文件同样容易。文档中对此进行了很好的解释。

【讨论】:

    【解决方案3】:
    print ' '.join(i + ' is lame.' for i in open(fname).read().split())
    

    【讨论】:

      【解决方案4】:
      >>> s="Jon Jane Joe Jack Jeremy "
      >>> s.replace(" ", " is lame. ")
      'Jon is lame. Jane is lame. Joe is lame. Jack is lame. Jeremy is lame. '
      

      【讨论】:

        【解决方案5】:

        请在下面找到一个非常基本的示例:

        outputLines = []
        with open('c:\\file.txt', 'r') as f:
            for line in f:
                if line.strip():
                    outputLines.append(' is lame. '.join(line.strip().split()))
        with open('c:\\file.txt', 'w') as f:
            for line in outputLines:
                f.write(line+'\n')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-10
          • 2017-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多