我想从控制台获取输入,该输入是带有多行的文本。由于我想在单个输入中完成所有操作,因此我必须在中间标记“ \ n”以表示不同的行。得到输入后,我想将文本保存在矩阵中,其中每一行是文本之间的一行,单词分开。
这是我这样做的功能:
def saveText(text):
text = text[6:len(text)-6]
line = 0
array = [[]]
cur = ""
for i in range (len(text)):
if (text[i] == '\n'):
line+=1
array.append([])
else:
if ((text[i] == ' ' or text[i] == ',' or text[i] == ';' or text[i] == '.') and cur != ""):
array[line].append(cur)
cur = ""
else:
cur += text[i]
return array
但是,当我打印变量array时,它显示为只有一行的矩阵,并且除了'\ n'被视为单词,它们也显示为'\ n'。
有人可以帮我吗?
您没有提供要测试的输入字符串,所以我自己做了一个。您可以使用.split()
分割新行和空格(或其他所需的任何内容)。
编辑:我想我现在明白你的意思。我认为您在尝试从用户获得输入时输入换行符\n
。 This isn't possible, but there is a workaround。我将来自该链接的答案集成到下面的代码中。
如果您希望用户在从他们那里获取输入时手动写\n
,则需要将text.splitlines()
更改为text.split('\\n'). You could also replace
\ nwith
\ nby using
text.replace('\ n','\ n')`。
但是,我认为仅使用如下所示的多行输入并像上面进一步讨论的那样,出错的可能性就较小。
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
input_text = '\n'.join(lines)
def save_text(text):
lines = text.splitlines()
matrix = []
for line in lines:
matrix.append(line.split(' '))
return matrix
print(save_text(input_text))
来自用户的输入看起来像这样:
hello how
are you
doing this fine
day?
输出:
[['hello', 'how'], ['are', 'you'], ['doing', 'on', 'this', 'fine'], ['day?']]
text = "line1: hello wolrd\nline2: test\nline2: i don't know what to write"
lines = text.split("\n")
lines = [x.split() for x in lines]
print(lines)
这将返回:
[['line1:', 'hello', 'wolrd'], ['line2:', 'test'], ['line2:', 'i', "don't", 'know', 'what', 'to', 'write']]
这个想法与Stuart的解决方案相同,只是效率更高一点。