简体   繁体   中英

Reading and print string x times

I have an assignment where I have a text file with a word on each line which forms a string. On some lines there are a number with which amount of times I have to print the string, separated by a comma and space and finish with a period

For instance:

Darth
Maul
is
a
bad
person
3

Which should then be: Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.

So far I'm quite stuck, I'm familliar with how to read the file line by line and I guess I have put the words in a list and determine when the number comes to iterate that list a number of times.

So far I have:

TEXT = input 'sith.txt'
words = []

with open(TEXT, 'r') as f:
    line = f.readline()
    for word in line:
        if string in word //is a string not an int
            words.append(string)
        else //print words + ', '

After this I'm pretty much stuck. Anyone out there that could point me in the right direction?

You can use joins and the end argument in print to accomplish this with a fewer number of lines.

lines = open("input.txt", "r").read().splitlines()
data, number = " ".join(lines[:-1]), int(lines[-1])

print(", ".join([data]*number), end=". ")

Which outputs:

Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.

example file: filename= text.txt

Darth
Maul
is
a
bad
person
3
Foo bar
baz
bla
5
another
demo
2

code:

import re

with open('text.txt') as fd:
    data = fd.read()

regex = re.compile(r'([^\d]+)(\d+)', re.DOTALL|re.MULTILINE)
for text, repeat in regex.findall(data):
    repeat = int(repeat)
    text = text.strip().replace('\n', ' ')
    print(', '.join([text] * repeat))

output:

Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person
Foo bar baz bla, Foo bar baz bla, Foo bar baz bla, Foo bar baz bla, Foo bar baz bla
another demo, another demo
# Read the TXT file into a list and strip whitespace from each line
with open('sith.txt', 'r') as infile:
    contents = [i.strip() for i in infile.readlines()]

# Get number of times to repeat phrase using the .pop method which returns the value at the index of an item and removes it from the list
repeat = int(contents.pop(-1))

# Create the phrase to repeat using the range() function and list comprehension
phrase = [' '.join(contents) for _ in range(repeat)]

# Join the phrases together with a comma and print the output
output = ', '.join(phrase)
print(output)

If the integer is guaranteed to come at the end, you can iterate until you reach an int. If there can be multiple chunks of words with an int at the end of each chunk of words, you can iterate line by line and try casting the line as an int.

TEXT = 'sith.txt'
words = []
multiple = 0

with open(TEXT, 'r') as f:
    # iterate through every line
    for line in f:
        # get rid of the '\n' at the end
        line = line.strip()

        # try casting the line as an int. If it's not an integer, it will raise a ValueError and skip to the except block
        try:
            multiple = int(line)
            for i in range(multiple):
                print(' '.join(words), end=', ')
            print() # for a new line at the end
            words = [] # reset words for new chunk

        # This except block gets run every time int() casting fails on a string
        except ValueError:
            words.append(line)
TEXT = 'sith.txt'                                      #your filename was off a bit
words = []
with open(TEXT, 'r') as f:                             #open it
    line = f.readlines()                               #read in the contents, save to "line"
    for word in line:                                  #for each word in the doc...
        if not word[:-1].isdigit():                    #if it's a word (we exclude last char because it's always "\n"
            words.append(word[:-1])                    #put it in the list
        else:                              
            for i in range(int(word)-1):               #we want to print it n-1 times with commas and once with the period.
                print(" ".join(words), end=", ")       #print with commas.
            print(" ".join(words), end=".\n")          #print with period.

That gives us... 在此输入图像描述

KuboMD and I have similar answers

TEXT = 'sith.txt'

with open(TEXT, 'r') as file:
    words = []
    for line in file:
        line = line.strip()
        if line.isdigit():
            segment = " ".join(words)
            for i in range (int(line) - 1):
               print(segment, sep =", ")
            print(segment + ".\n")
        else:
            segment.append(line)

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