首页 > 解决方案 > 如何从输入中删除所有可能的无关空格、制表符、下一行和其他内容以清理标准输入 python 输入?

问题描述

我已经尝试了以下不同变体的代码,但无济于事。用户可以像这样输入非结构化数据

"4231, 312 1231212,12 1 23 123,12,3,123 123 1,2, 3123",

我正在尝试清理它

[4231, 312, 1231212, 12, 1, 23, 123, 12 , 3, 123, 123, 1, 2, 3123]

代码:

print("Please enter the numbers (separated by space, comma or
    line) then press CMD/CTRL D :")
num_input = sys.stdin.read()

def convert_number_input(integer_inputs):
"""Takes integer inputs separated by comma or space or line as a string and converts to list of operable integers.
First checks for comma typos in input, then removes spaces and irrelevant data, then finally converts to integer.
If just one number is the input it simply converts it to integer list"""

first_input = re.sub(r"[\n\t\s]", " ", integer_inputs)

all_comma_input = first_input.strip()

stripping_input = all_comma_input.replace(' ', ',')

fresh_input = stripping_input.strip(',')

clean_integer_inputs = fresh_input.replace(',,,', ',')

very_clean_integer_inputs = clean_integer_inputs.replace(',,', ',')

split_input = very_clean_integer_inputs.split(',')

final_input = list(map(int, split_input))

return final_input

final_num_input = convert_num_input(num_input)

print(final_num_input)

标签: pythonstringlistsplit

解决方案


猜你可以list comprehension使用

>>> [int(z.strip()) for z in x.replace(',', " ").split(' ') if z.strip()]

[4231, 312, 1231212, 12, 1, 23, 123, 12, 3, 123, 123, 1, 2, 3123]

或者,如果需要regex,使用\s+

>>> list(map(int, re.split(r'\s+', x.replace(',',''))))

[4231, 312, 123121212, 1, 23, 123123123, 123, 12, 3123]

推荐阅读