1

我需要使用字典替换文件中的单词 AAAA:

字典.txt

AXF1
ZCFA
ZCCC

字典大约1500字。我需要用 AXF1 替换 AAAA,然后我需要找到下一个 AAAA 并用 ZCFA 替换......知道我该怎么做吗?我发现的一切都是如何替换的:

AAA1:AXF1
AAA2:ZCFA
etc...
4

3 回答 3

1

就像是:

# Read dictionary into memory
dictionary = [line.strip() for line in open('dictionary.txt')]

# Assuming a bit of a wrap around may be required depending on num. of AAAA's
from itertools import cycle
cyclic_dictionary = cycle(dictionary)

# Read main file
other_file = open('filename').read()

# Let's replace all the AAAA's
import re
re.sub('A{4}', lambda L: next(cyclic_dictionary), other_file, flags=re.MULTILINE)
于 2012-06-24T13:12:02.280 回答
1

这可能对您有用(GNU sed):

cat <<\! >dictionary.txt
> AXF1
> ZCFA
> ZCCC
> !
cat <<\! >file.txt
> a
> b
> AAAA
> c
> AAAA
> d
> AAAA
> !
sed -e '/AAAA/{R dictionary.txt' -e ';d}' file.txt
a
b
AXF1
c
ZCFA 
d 
ZCCC
于 2012-06-24T18:09:55.320 回答
1
awk 'FNR == NR {list[c++] = $1; next}
{
    while (sub("AAAA", list[n++])) {
        n %= c
    }
    print
}' list.txt inputfile.txt
于 2012-06-24T13:32:48.160 回答