【问题标题】:Deleting every second occurence of a word in a txt file (Python)删除文本文件中每个第二次出现的单词(Python)
【发布时间】:2013-10-02 12:33:10
【问题描述】:

我想删除文件中出现的一些“名称”一词,但不删除其他。我猜最好的方法是使用某种累加器模式,但我不确定如何实现它。

到目前为止我有:

f = open("old_text.txt")
number = f.read()
f.close

name_occurrence = (number.count("Courtney"))

我只是使用“Courtney”作为文件中实际名称的示例。我想以某种方式删除“Courtney”这个词的每一个奇数出现,但不是偶数,即number.count迭代它为“Courtney”的每个实例分配一个数字值,然后一些代码删除出现的“Courtney”这个词值为 1,3,5,7...

感谢您的帮助,

蓬松

【问题讨论】:

  • 如果你创建一个 for 循环来搜索字符串,如这个答案:stackoverflow.com/questions/2768628/… 然后你可以跟踪你是否删除了姓氏并选择删除你的姓氏'在
  • 感谢您的链接。它很有帮助,我可以看到它是如何使用的,但我认为我对编程的理解还为时过早,无法自己实现它。我可能正在尝试做一些过于复杂的事情,因为我只在编程/python 工作了几个月。
  • 试试吧!可能发生的最坏情况是什么?如果您遇到错误,请在此处发布您正在尝试的代码和错误,人们会很乐意为您提供帮助(当然,在您进行一些研究并尝试自己修复它之后)。就您的问题而言,它可能已关闭,因为它不够具体...

标签: python string accumulator


【解决方案1】:

未测试,但您可以尝试这样的正则表达式:

import re

with open("old_text.txt") as f:
   txt = f.read()
   new_txt=re.sub(r'(\bCourtney\b.*?)(\s*\Courtney\b\s*)','\1',txt,re.S)

如果你想要一个动态字符串(即其中有一个变量):

import re

name='Courtney'

with open("old_text.txt") as f:
   txt = f.read()
   new_txt=re.sub(r'(\b{}\b.*?)(\s*\{}\b\s*)'.format(name,name),'\1',txt,re.S)

【讨论】:

    【解决方案2】:

    这很难看,但它可以工作而且它是纯 python

    文件names.txt(我在名字Courtney前面放了数字以便更容易判断哪些被删除):

    11111 Courtney Emma Jessica 22222 Courtney Ashley Amanda Jennifer 
    Sarah Michael 33333 Courtney Christopher Matthew Joshua David
    Emma Jessica Ashley Amanda Jennifer 44444 Courtney 
    Sarah 55555 Courtney Michael 66666 Courtney Christopher 
    77777 Courtney Emma Jessica Ashley Amanda Jennifer 88888 Courtney 
    Sarah Michael 99999 Courtney Christopher Matthew
    

    代码:

    f = open("names.txt",'r')
    splited_lines = []
    name_occurrence = 0
    name = "Courtney"
    
    #create list of lines where line is list of words
    index = 1
    for line in f:
        name_occurrence += line.count(name)
        splited_line = line.split()
        splited_lines.append(splited_line)
    f.close
    
    #delete every even name (Courtney)
    #if you want every odd to be deleted set word_counter on 0
    word_counter = -1    
    for i,line in enumerate(splited_lines):
        for j,word in enumerate(line):
            if (name in word):
                word_counter += 1 
                if (word_counter%2 == 0):
                    splited_lines[i][j] = word.replace(name, "")
    
    #create string to write back to file
    text_to_save = ""
    for line in splited_lines:
        for word in line:
            if word != "":
                text_to_save += word + " "
        text_to_save += "\n"
    
    #write to file
    with open('names.txt', 'w') as f:
        f.writelines(text_to_save)
    

    我希望这会有所帮助。有什么不明白的欢迎追问。

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2021-12-11
      • 1970-01-01
      • 2011-12-10
      相关资源
      最近更新 更多