简体   繁体   中英

How Can I read a string from a txt file line by line and run it with a function?

I have a txt file named a.txt . In this file a has a string per line. I want to append these strings line by line to the keyword = {} dict and run my double_letter function for each line of string. How can I do it?

my double_letter function:

keyword = {}

def double_letter():
    print("\nDouble Letter:\n")
    idx = random.randint(0, len(keyword) - 1)
    keyword = keyword[:idx] + keyword[idx] + keyword[idx:]
    print(keyword)

You can open, read and print the contents of a txt file as follows:

f = open("a.txt", "r")
for line in f:
    print(line)

You can add in your function for each run through the for loop, ie calling it during each line of the text:

f = open("a.txt", "r")
for line in f:
    print(line)
    double_letter()

IIUC

Code

import random

def double_letter(line):
    '''
        Repeats random letter in line
    '''
    if line:
        idx = random.randint(0, len(line) - 1)
        return line[:idx] + line[idx] + line[idx:]
    else:
        return line     # does nothing with blank lines
    
with open("a.txt", "r") as f:                # with preferred with open file
    keyword = {}                             # setup results dictionary
    for line in f:
        line = line.rstrip()                 # remove the '\n' at the end of each line
        keyword[line] = double_letter(line)  # add line with it's repeat to dictionary
        
print(keyword)    

File a.txt

Welcome
To
Stackoverflow

Output

{'Welcome': 'Welcomee', 'To': 'Too', 'Stackoverflow': 'Stackoverfloow'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM