读取并打印字符串x次

时间:2019-01-10 14:40:36

标签: python file for-loop if-statement readlines

我有一个作业,其中有一个文本文件,在每行上都有一个单词,形成一个字符串。在某些行上,有一个数字,我必须打印该字符串的次数,并用逗号和空格隔开,并以句点结束

例如:

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 :(得分:3)

您可以在打印中使用join和end参数来完成此操作,而行数更少。

require

哪个输出:

  

达斯·莫尔(Darth Maul)是一个坏人,达斯·莫尔(Darth Maul)是一个坏人,达斯·莫尔(Darth Maul)是一个坏人。

答案 1 :(得分:2)

示例文件:filename = 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

答案 2 :(得分:2)

var vs = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 }
var letters = [];
var numbers = [];
var phrase = "";

for (var key in vs) {
    letters.push(key);
    numbers.push(vs[key]);
}

for (var i = 1; i < letters.length; i += 2) {
    if (numbers[i-1] > numbers[i]) {
        phrase = phrase + letters[i-1];
    } else {
        phrase = phrase + letters[i];
    }
}

答案 3 :(得分:1)

如果保证整数末尾,则可以迭代直到达到整数。如果每个单词块的末尾可以有多个带有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)

答案 4 :(得分: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.

那给了我们... enter image description here

答案 5 :(得分:1)

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