Чтение и печать строки x раз - PullRequest
0 голосов
/ 10 января 2019

У меня есть задание, где у меня есть текстовый файл со словом в каждой строке, которая образует строку. В некоторых строках есть число, с которым я должен печатать строку раз, разделенный запятой и пробелом и заканчивающийся точкой

Например:

Darth
Maul
is
a
bad
person
3

Что тогда должно быть: Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.

Пока я довольно застрял, я знаком с тем, как читать файл строка за строкой, и я предполагаю, что я поместил слова в список и определил, когда число придет, чтобы повторить этот список несколько раз.

Пока у меня есть:

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 + ', '

После этого я почти застрял. Кто-нибудь, кто мог бы указать мне правильное направление?

Ответы [ 6 ]

0 голосов
/ 10 января 2019

Вы можете использовать соединения и аргумент конца в печати, чтобы выполнить это с меньшим количеством строк.

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

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

Какие выходы:

Дарт Мол - плохой человек, Дарт Мол - плохой человек, Дарт Мол - плохой человек.

0 голосов
/ 10 января 2019
# 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)
0 голосов
/ 10 января 2019

у KuboMD и у меня похожие ответы

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)
0 голосов
/ 10 января 2019

файл примера: имя файла = text.txt

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

код:

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))

выход:

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
0 голосов
/ 10 января 2019
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.

Это дает нам ... enter image description here

0 голосов
/ 10 января 2019

Если целое число гарантированно придет в конце, вы можете выполнять итерации, пока не достигнете целого числа. Если может быть несколько фрагментов слов с int в конце каждого фрагмента слов, вы можете перебирать строку за строкой и пытаться приводить строку как 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)
...