我有如下所示的数据:
1937 Paredes 3-1
1939 Suazo 2-0
1941 Fernandez 4-0
1944 Wilchez 2-1
…
2017 Miralles 5-7我想把每一行都当作一行文本来读。查找后跟数字、字符或任何非空格符号的空格的任意实例。按以下方式将该数字、字符或任何非空格符号前面的空格替换为"|“:
1937 |Paredes |3-1
1939 |Suazo |2-0
1941 |Fernandez |4-0
1944 |Wilchez |2-1
...
2017 |Miralles |5-7你知道如何在SAS或Python中这样做吗?
发布于 2021-06-17 04:32:26
您可以使用re.sub匹配一个空格,并在右侧断言一个非空格字符:
import re
test_str = ("1937 Paredes 3-1\n\n"
"1939 Suazo 2-0\n\n"
"1941 Fernandez 4-0\n\n"
"1944 Wilchez 2-1")
result = re.sub(r" (?=\S)", "|", test_str)
if result:
print (result)输出
1937|Paredes|3-1
1939|Suazo|2-0
1941|Fernandez|4-0
1944|Wilchez|2-1或查找不带换行符的多个空格字符
result = re.sub(r"[^\S\r\n]+(?=\S)", "|", test_str)发布于 2021-06-17 05:20:43
我不明白保留其他空间的必要性。为什么不把它们全部删除呢?
data _null_;
infile 'have.txt' truncover;
file 'want.txt' dsd dlm='|';
input (var1-var3) (:$100.);
put var1-var3;
run;结果
1937|Paredes|3-1
1939|Suazo|2-0
1941|Fernandez|4-0
1944|Wilchez|2-1
2017|Miralles|5-7https://stackoverflow.com/questions/68009607
复制相似问题