[英]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.