在Python中,我只想从字符串中提取字符。
考虑我有以下字符串,
input = "{('players',): 24, ('year',): 28, ('money',): 19, ('ipod',): 36, ('case',): 23, ('mini',): 46}"
我想要的结果是,
output = "players year money ipod case mini"
我尝试只考虑字母来拆分,
word1 = st.split("[a-zA-Z]+")
但是分裂并没有发生。
你可以用 re 来做到这一点,但是字符串分割方法不接受正则表达式,它需要一个字符串。
这是使用 re 完成此操作的一种方法:
import re
word1 = " ".join(re.findall("[a-zA-Z]+", st))
string.split() 不接受正则表达式。 你想要这样的东西:
re.split("[^a-zA-Z]*", "your string")
并获取字符串:
" ".join(re.split("[^a-zA-Z]*", "your string"))
我认为你想要所有的单词,而不是字符。
result = re.findall(r"(?i)\b[a-z]+\b", subject)
说明:
"
\b # Assert position at a word boundary
[a-z] # Match a single character in the range between “a” and “z”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\b # Assert position at a word boundary
"
这样做怎么样?
>>> import ast
>>> " ".join([k[0] for k in ast.literal_eval("{('players',): 24, ('year',): 28, ('money',): 19, ('ipod',): 36, ('case',): 23, ('mini',): 46}").keys()])
'case mini year money ipod players'
您可以采用迭代字符串的方法,并使用
isalpha
函数来确定它是否是字母字符。如果是,您可以将其附加到输出字符串中。
a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
if i.isalpha():
q = "".join([q,i])
或者如果您想要所有字符,无论单词或空格
a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
if i.isalpha():
q = "".join([q,i])
打印q '一些字符串'
import re
string = ''.join([i for i in re.findall('[\w +/.]', string) if i.isalpha()])
#'[\w +/.]' -> it will give characters numbers and punctuation, then 'if i.isalpha()' this condition will only get alphabets out of it and then join list to get expected result.
# It will remove spaces also.
我妈妈说我有一天会死