python - Match from list -
i still learning python, trying things.
i have code search word 'lorem' in text , replace random word list. working.
what wanna how check if word list (words = ['and', 'a', 'is', 'the']) in text , replace word list (t = ['text', 'replace', 'word']).
i wanna replace 'lorem' variable or loop thru list or open txt file words check.
res = re.sub('lorem', lambda x: random.choice(t), text)
if possible if can show me 3 options:
-loop through list -variable -open file words inside
or maybe there other, better way?
thanks!
here full code
import re import random t = ['text', 'replace', 'word'] text = '''lorem ipsum dummy text of printing , typesetting industry. lorem ipsum has been industry's standard dummy text ever since 1500s, when unknown printer took galley of type , scrambled make type specimen book. has survived not 5 centuries, leap electronic typesetting, remaining unchanged. popularised in 1960s release of letraset sheets containing lorem ipsum passages, , more desktop publishing software aldus pagemaker including versions of lorem ipsum''' words = ['and', 'a', 'is', 'the'] res = re.sub('lorem', lambda x: random.choice(t), text) print(res)
the following code replace word in text
in words
random word replacement
.
import random replacement = ['text', 'replace', 'word', 'list'] text = '''lorem ipsum dummy text of printing , typesetting industry. lorem ipsum has been industry's standard dummy text ever since 1500s, when unknown printer took galley of type , scrambled make type specimen book. has survived not 5 centuries, leap electronic typesetting, remaining unchanged. popularised in 1960s release of letraset sheets containing lorem ipsum passages, , more desktop publishing software aldus pagemaker including versions of lorem ipsum''' # open('ipsum.txt') tf: text = tf.read(none) words = ['and', 'a', 'is', 'the'] text_words = text.split() ti, tw in enumerate(text_words): if tw in words: text_words[ti] = random.choice(replacement) print(' '.join(text_words)) # possible output: # lorem ipsum word dummy text of list printing replace typesetting industry. lorem ipsum has been replace industry's standard dummy text ever since text 1500s, when unknown printer took word galley of type list scrambled make word type specimen book. has survived not 5 centuries, text leap electronic typesetting, remaining unchanged. popularised in word 1960s replace release of letraset sheets containing lorem ipsum passages, replace more desktop publishing software aldus pagemaker including versions of lorem ipsum
if want take replacement
@ same index in words
, can use loop:
for ti, tw in enumerate(text_words): try: wi = words.index(tw) except valueerror: pass else: text_words[ti] = replacement[wi] print(' '.join(text_words)) # result: # lorem ipsum word dummy text of list printing text typesetting industry. lorem ipsum has been list industry's standard dummy text ever
Comments
Post a Comment