读取并打印字符串 x 次
Reading and print string x times
我有一个作业,其中我有一个文本文件,每行都有一个单词构成一个字符串。在某些行上有一个数字,我必须打印该字符串的次数,用逗号和 space 分隔并以句点
结束
例如:
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 + ', '
在这之后我几乎被困住了。任何人都可以指出我正确的方向吗?
如果整数保证在最后,你可以迭代直到你到达一个整数。如果可以有多个词块,每个词块的末尾都有一个 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.
这给了我们...
示例文件:文件名=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
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)
# 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)
您可以在 print 中使用连接和结束参数,以更少的行数完成此操作。
lines = open("input.txt", "r").read().splitlines()
data, number = " ".join(lines[:-1]), int(lines[-1])
print(", ".join([data]*number), end=". ")
输出:
Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.
我有一个作业,其中我有一个文本文件,每行都有一个单词构成一个字符串。在某些行上有一个数字,我必须打印该字符串的次数,用逗号和 space 分隔并以句点
结束例如:
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 + ', '
在这之后我几乎被困住了。任何人都可以指出我正确的方向吗?
如果整数保证在最后,你可以迭代直到你到达一个整数。如果可以有多个词块,每个词块的末尾都有一个 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.
这给了我们...
示例文件:文件名=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
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)
# 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)
您可以在 print 中使用连接和结束参数,以更少的行数完成此操作。
lines = open("input.txt", "r").read().splitlines()
data, number = " ".join(lines[:-1]), int(lines[-1])
print(", ".join([data]*number), end=". ")
输出:
Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.