python - 如何从输入中删除所有可能的无关空格、制表符、下一行和其他内容以清理标准输入 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)
解决方案
猜你可以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]
推荐阅读
- python-3.x - Pythonw, pyw, & arg, /B 不会让 python 的 http-server 在后台运行
- julia - 二项式实验
- json - 如何转换 AWS CloudTrail JSON 输出时间
- java - 多线程矩阵加法比java中的单线程版本花费更长的时间
- java - Java:如何使用线程和用户输入显示奇数和偶数
- blazor - Blazor WebAssembly 托管 API URL
- java - 将列表中的一个值与另一个列表的子列表中的另一个值进行比较java 8
- python-3.x - 使用python将字符串列表转换为具有相同长度的字节数组
- regex - 正则表达式提取带和不带空格的字符串
- reactjs - 从 API 获取数据返回未定义