【问题标题】:Python 3.2 Replace all words in a text document that are a certain length?Python 3.2 替换文本文档中具有一定长度的所有单词?
【发布时间】:2012-11-09 18:21:33
【问题描述】:

我需要用不同的单词替换文本文档中长度为 4 的所有单词。

例如,如果文本文档包含短语“我喜欢吃非常热的汤”,那么“喜欢”、“非常”和“汤”等词将被替换为“某物”

然后,它需要使用更改后的短语创建一个新文档,而不是覆盖原始文本文档。

这是我目前所拥有的:

def replacement():  
    o = open("file.txt","a") #file.txt will be the file containing the changed phrase
    for line in open("y.txt"):  #y.txt is the original file
        line = line.replace("????","something")  #see below
        o.write(line + "\n")
    o.close()

我试过改变“??????”像

(str(len(line) == 4)

但这没有用

【问题讨论】:

    标签: python string python-3.2


    【解决方案1】:

    首先让我们创建一个函数,如果给定一个长度为 4 的单词,则返回 something,否则返回它:

    def maybe_replace(word, length=4):
      if len(word) == length:
        return 'something'
      else:
        return word
    

    现在让我们来看看你的 for 循环。在每次迭代中,您都有一行原始文件。让我们把它分解成单词。 Python 为我们提供了可以使用的split 函数:

       split_line = line.split()
    

    默认是在空白处分割,这正是我们想要的。有more documentation,如果你想要的话。

    现在我们要获取在每个单词上调用 maybe_replace 函数的列表:

      new_split_line = [maybe_replace(word) for word in split_line]
    

    现在我们可以使用join method 将这些备份连接在一起:

      new_line = ' '.join(new_split_line)
    

    并将其写回我们的文件:

      o.write(new_line + '\n')
    

    所以我们的最终函数将是:

    def replacement():  
      o = open("file.txt","a") #file.txt will be the file containing the changed phrase
      for line in open("y.txt"):  #y.txt is the original file
        split_line = line.split()
        new_split_line = [maybe_replace(word) for word in split_line]
        new_line = ' '.join(new_split_line)
        o.write(new_line + '\n')
      o.close()
    

    【讨论】:

    • 这不会保留单词之间的额外空格。虽然这在许多情况下都可以,但并非完全如此。
    • 完美解决方案!解释得很好,效果很好。谢谢大佬
    【解决方案2】:
    with open('file.txt', 'a') as write_file:
        with open('y.txt') as read_file:
            for line in read_file.readlines():
                # Replace the needed words
                line = line.replace('????', 'something')
                write_file.write(line)
    

    【讨论】:

      【解决方案3】:

      这将保留您拥有的额外空间,而使用 str.split() 的其他解决方案则不会。

      import re
      
      exp = re.compile(r'\b(\w{4})\b')
      replaceWord = 'stuff'
      with open('infile.txt','r') as inF, open('outfile.txt','w') as outF:
          for line in inF:
              outF.write(exp.sub(replaceWord,line))
      

      这使用正则表达式来替换文本。这里使用的正则表达式有三个主要部分。第一个匹配单词的开头:

      \b
      

      第二部分正好匹配四个字母(所有字母数字字符和_):

      (\w{4})
      

      最后一部分和第一部分一样,它匹配一个单词的结尾

      \b
      

      【讨论】:

        【解决方案4】:

        这似乎是家庭作业,所以这里有一些关键概念。

        当您读取文件时,您会得到linesstrings。您可以使用名为.split() 的字符串方法将line 拆分为list,就像这样。 words = line.split()。这将创建一个单词列表。

        现在,list可迭代,这意味着您可以在其上使用 for 循环,并一次对 list 的一项进行操作。您想检查word 的长度,因此您必须使用循环遍历words,并对其进行处理。您已经接近弄清楚如何使用len(word) 检查单词的长度。

        您还需要一个地方来随时存储您的最终信息。在循环之外,您需要为结果创建一个list,并为您在进行过程中检查的单词创建.append()

        最后,您需要为文件中的每个line 执行此操作,这意味着迭代文件的 for 循环。

        【讨论】:

          猜你喜欢
          • 2018-08-15
          • 2022-12-11
          • 1970-01-01
          • 2018-07-22
          • 1970-01-01
          • 1970-01-01
          • 2019-11-18
          • 2011-09-06
          • 1970-01-01
          相关资源
          最近更新 更多