2

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Thomas Bengtsson
  • 399
  • 2
  • 10
  • 22

6 Answers6

3

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.

Grant Williams
  • 1,469
  • 1
  • 12
  • 24
2

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
dopstar
  • 1,478
  • 10
  • 20
  • Don't forget to close you file. You should use `with open` so it's no even something to remember. – GranolaGuy Jan 10 '19 at 15:03
  • I think you need to add end="." in your print statement. I think the sentence is supposed to end with a "." – Grant Williams Jan 10 '19 at 15:58
  • @GrantWilliams adding `end='.'` will make those 3 lines be all in one line. If the full stop is so important it can be concatenated on the result like this: `print(', '.join([text] * repeat) + '.')` – dopstar Jan 11 '19 at 11:16
2
# 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)
amickael
  • 21
  • 1
  • 3
1

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)
Endyd
  • 1,249
  • 6
  • 12
1
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... enter image description here

KuboMD
  • 684
  • 5
  • 16
1

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)
GranolaGuy
  • 133
  • 12