SAS/Python:查找任何 space 后跟非 space 字符串并用不同的值替换 space
SAS/Python: Find any spaces followed by a non-space string and replace space with a different value
我有这样的数据:
1937 Paredes 3-1
1939 Suazo 2-0
1941 Fernandez 4-0
1944 Wilchez 2-1
…
2017 Miralles 5-7
我想将每一行都读成一行文本。查找 space 后跟数字、字符或任何非 space 符号的任何实例。将该数字、字符或任何非 space 符号前面的 space 替换为“|”通过以下方式:
1937 |Paredes |3-1
1939 |Suazo |2-0
1941 |Fernandez |4-0
1944 |Wilchez |2-1
...
2017 |Miralles |5-7
知道如何在 SAS 或 Python 中做到这一点吗?
您可以使用 re.sub 匹配 space 并断言右侧的非白色 space 字符:
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
或者找到多个没有换行符的白色space字符
result = re.sub(r"[^\S\r\n]+(?=\S)", "|", test_str)
我不明白保留其他空格的必要性。为什么不将它们全部删除?
data _null_;
infile 'have.txt' truncover;
file 'want.txt' dsd dlm='|';
input (var1-var3) (:0.);
put var1-var3;
run;
结果
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
我想将每一行都读成一行文本。查找 space 后跟数字、字符或任何非 space 符号的任何实例。将该数字、字符或任何非 space 符号前面的 space 替换为“|”通过以下方式:
1937 |Paredes |3-1
1939 |Suazo |2-0
1941 |Fernandez |4-0
1944 |Wilchez |2-1
...
2017 |Miralles |5-7
知道如何在 SAS 或 Python 中做到这一点吗?
您可以使用 re.sub 匹配 space 并断言右侧的非白色 space 字符:
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
或者找到多个没有换行符的白色space字符
result = re.sub(r"[^\S\r\n]+(?=\S)", "|", test_str)
我不明白保留其他空格的必要性。为什么不将它们全部删除?
data _null_;
infile 'have.txt' truncover;
file 'want.txt' dsd dlm='|';
input (var1-var3) (:0.);
put var1-var3;
run;
结果
1937|Paredes|3-1
1939|Suazo|2-0
1941|Fernandez|4-0
1944|Wilchez|2-1
2017|Miralles|5-7