Python 如果在列表中,正则表达式将在论文中添加单词

Python 如果在列表中,正则表达式将在论文中添加单词,python,regex,Python,Regex,我是python和正则表达式的初学者。我有一张清单:[猫、狗、鸟、鸭] 如果猫在列表中,它应该将“动物”添加到paranthesis中现有的宠物中,如:petsanimal 如果猫和狗在列表中,它应该是:宠物,动物 文本文件: My favourite pets pets() My favourite pets pets(animal,animal) 预期的文本文件: My favourite pets pets() My favourite pets pets(animal,animal

我是python和正则表达式的初学者。我有一张清单:[猫、狗、鸟、鸭] 如果猫在列表中,它应该将“动物”添加到paranthesis中现有的宠物中,如:petsanimal 如果猫和狗在列表中,它应该是:宠物,动物

文本文件:

My favourite pets
pets()
My favourite pets
pets(animal,animal)
预期的文本文件:

My favourite pets
pets()
My favourite pets
pets(animal,animal)
编码

import re
list=['cat','dog','bird','cow'] 
with open('te.txt','r+') as f:
    a = [x.rstrip() for x in f]
    if 'cat' in list:
        item='animal'
        add=(r'^pets (.*)', item)
        f.write('pets(' + item)
    if 'dog' in list:
        item='animal'
        add=(r'^pets (.*)', item)
        f.write('pets(' + item)

我做这件事已经疯了,请帮我修改我的代码。请回答

我不知道你为什么要使用正则表达式。您可以读取文本文件,通过字符串切片删除“我最喜欢的宠物”和“宠物”文本,构建列表并将其写回文件。它不够复杂,不需要正则表达式

我想出了一个快速的替代方案:

MY_NEW_LIST = ['cat', 'dog', 'bird', 'cow']
ANIMAL_PETS = ['cat', 'dog']
PETS_FILE   =  'animals.txt'

# open the existing file, and get the line with `pets(…)`
with open(PETS_FILE, 'r+') as f:
    existing_animal_str = f.readlines()[1]

# get the list of animals from `pets(…)`
existing_animals = pets_line[5:-1]
list_of_animals  = [i for i in existing_animals.split(',') if len(i) > 0]

# add the new animals to the list
for pet in ANIMAL_PETS:
    if pet in MY_NEW_LIST:
        list_of_animals.append('animal')

# construct a new string to put back into `pets(…)`
final_animal_str = ', '.join(list_of_animals)

# write the new string back to the file
with open(PETS_FILE, 'w+') as f:
    f.write('My favourite pets\npets(%s)' % final_animal_str)
前三行包含一些常量:动物列表、将动物添加到宠物行的宠物列表以及文本文件的名称


作为补充说明,变量名可能需要做一些工作。由于list是一个内置函数的名称,add是非常通用的,因此使用这样的变量名会导致问题。使用更具体的变量名。

听起来像是在文件中查找并替换文本,您可以使用str.replace并重写它

文本文件:

My favourite pets
pets()
My favourite pets
pets(animal,animal)
输出文本文件:

用于正则表达式

import re
listAnimal = ['cat', 'dog', 'bird', 'cow'] 
with open('te.txt','r+b') as f:
    listsAppendAnimal = []
    text = 'pets('
    if 'cat' in listAnimal:
        listsAppendAnimal.append('animal')
    if 'dog' in listAnimal:
        listsAppendAnimal.append('animal')
    allText = f.read()
    allText = re.sub(r'pets\(.*?\)', 'pets(' + ', '.join(listsAppendAnimal) + ')', allText)
    f.seek(0)
    f.truncate()
    f.write(allText)
    f.close()
-


注意,

您不使用正则表达式。我看不出使用它们有什么意义。