Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

python - need to iterate over two lists in order to randomize numbers found in text

My goal is to search a text, find all numbers, and randomize each number. The numbers are not written as digits, but as words. I've created a list for the numbers and used the split method to turn the text into a different list. I need to compare each word in the text to all elements in the numbers list, and if any match, randomize that number. I've tried multiple ways to iterate over the two lists, for example,

            i = iter(digits_list)
            next(i)

I also tried the zip method but I couldn't get it to work, it gave tuples but not every combination of tuple.

The text in my file is this:

    [{"text": "ZIP code for your address? Three, zero, zero five, eight. bye.", "s": 1090, "speaker": "Unknown", "e": 1787571}]

The code is like this:

    def digit_randomize_json(list_path, jsonDir, output):


        digits_list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", 
    "ten", "zero"]
        generated_digit = (random.choice(digits_list))

        with open (list_path, 'r') as list_file:
            for raw_filename in list_file:
                filename = raw_filename.rstrip()
                pathandfile = os.path.join(jsonDir, filename)
                f = open(pathandfile)
                data = json.load(f)
                f.close()
                words = data['transcript']['turns'][0]['text']
                words = words.split()

                for idx, word in enumerate(words):
                    words[idx] = words[idx].lower()
                    if words[idx] in digits_list:
                        words[idx] = generated_digit 
                        print words[idx]

What I would expect to have ultimately as a result is something like "[{"text": "ZIP code for your address? four, four, five nine, zero. bye.", "s": 1090, "speaker": "Unknown", "e": 1787571}]

In the short term I just want to succeed in having it print out all the numbers in the text, randomized.

Can someone suggest how to iterate over both the list and check every possible combination in order to identify the numbers and then randomize them?

question from:https://stackoverflow.com/questions/65928141/need-to-iterate-over-two-lists-in-order-to-randomize-numbers-found-in-text

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...