Home > Net >  How can I build a string dynamically based on N pre-processed strings? (where N is unknown)
How can I build a string dynamically based on N pre-processed strings? (where N is unknown)

Time:01-08

My program receives a stream of Reddit comments as strings. It looks for words which meet a certain requirement (checked via RegEx); once it has found one it is processed. I want to make a reply using the processed words.

At the moment the program creates a reply for each word which has met the requirement. However, a given comment may contain N number of words that meet the requirement - which would result in N replies.

Instead, I would like to build 1 reply per comment, which contains N processed words. How could I do this?

Below is a minimal excerpt of the code I have now.

for comment in subreddit.stream.comments():  # get the comments
    for word in comment.body.split():  # go over each word
         if re.search(re, word):  # see wether any meet the requirement
              word_new = process(word)  # process any words which do
              reply = f"A {word} is a(n) {word_new}."  # build reply

Desired reply:

f"A {word} is a(n) {word_new}."
f"A {word} is a(n) {word_new}."
...
f"A {word} is a(n) {word_new}."
# N times, where N is the number of words which meet the requirement in a comment

CodePudding user response:

You can build reply in inner loop and return only in outer. Also note that using precompiled regex is noticeable faster.

import re

regex = re.compile(r'WhatShouldBeHere')
for comment in subreddit.stream.comments():
    reply_data = [word for word in comment.body.split() 
                  if regex.search(word)]
    reply = '\n'.join(f'A {word} is a(n) {process(word)}.'
                      for word in reply_data)

  •  Tags:  
  • Related