Python中的迭代正则表达式:查找和替换

时间:2014-12-15 12:30:26

标签: python regex foreach

这是其中之一"我知道如何在C"输入问题。 :p  我问这个类似的问题,所以我没有找到我想要的特定方面。

我基本上希望找到和替换也具有所有格形式的物品。所以如果有一只兔子"在列表中,还有一只兔子"然后替换" rabbit"用一系列星号。

有些事情:

#!/usr/bin/env python

import re

text = open("list.txt", "w")

for line in text:
        test = line
        if re.match(test+"'", line) or re.match(test+"'s", line):
            line = "****" 

然而,这显然不会起作用,因为每个机制都会将行用于迭代和模式匹配。

2 个答案:

答案 0 :(得分:2)

with open('file.txt') as f:
    # Remove the \n characters at the end of each line
    all_lines = [x.strip() for x in f.readlines()]
    for line in all_lines:
        # Check for presence of word' or word's 
        if line+"'" in all_lines or line+"'s" in all_lines:
            print('****')
        else:
            print(line)

值得注意的是,这是一种非常强力的做法,对于巨大的列表需要更长的时间(它将文件加载到内存中),但应该给你一个想法。

答案 1 :(得分:1)

您可以使用str.endswith:

text = open("list.txt", "r")

for line in text:
    test = line.strip()
    if test.endswith("'s"):
        line = "****" 

这里我已经解释了为什么你的代码无法运行:

替换这个:

test = line

为:

test = line.strip()   # to remove new line character

因此,如果您不删除换行符

,那么您的测试将为rabbit\n'

您还需要在阅读模式下打开文件

text = open("list.txt",'r')

你匹配不会起作用,想一想:

假设test =“rabbit's”

    test+"'" will give you `rabbit's'`