[英]Reading and print string x times
我有一个作业,我有一个文本文件,每行都有一个单词形成一个字符串。 在某些行上有一个数字,我必须打印字符串,用逗号和空格分隔,并以句点结束
例如:
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 + ', '
在此之后,我几乎陷入困境。 谁在那里可以指出我正确的方向?
您可以在print中使用连接和结束参数,以减少行数。
lines = open("input.txt", "r").read().splitlines()
data, number = " ".join(lines[:-1]), int(lines[-1])
print(", ".join([data]*number), end=". ")
哪个输出:
Darth Maul是个坏人,Darth Maul是个坏人,Darth Maul是个坏人。
示例文件: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
# 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)
如果保证最后得到整数,则可以迭代直到达到int。 如果在每个单词块的末尾可以存在多个带有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)
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.
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.