如果字符串没有空格,则从字符串中获取特定单词

2024-05-23 03:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这些弦:

552D3AE5|HellothisIsATest__**wordIWant**|someotherstuff|0
3685248S|HellomynameIsAlex__**wordIWant2**|someotherstuff|0
8963252A|HelloiAm25YearsOld__**wordIWant3**|someotherstuff|0

基本上我想从这个字符串中“提取”单词

不幸的是,所有这些都没有空格,所以我不能使用split。 我试过使用startswith(),但只有在乞讨中才有效。你知道吗

所有字符串都具有相同的模板

.....|Hello........|.....

Tags: 字符串模板hello单词split空格startswithsomeotherstuff
3条回答

您可以在(?<![A-Za-z0-9])wordIWant\w*上执行regex搜索,使用右侧的\w*来允许可能更长的单词:

inp = "8963252A|HelloiAm25YearsOld__wordIWant3|someotherstuff|0"
matches = re.findall(r'(?<![A-Za-z0-9])wordIWant\w*', inp)
print(matches)

['wordIWant3']

按管道拆分,然后抓住每个字符串的第二个条目,按双下划线拆分,然后取后一个条目,就完成了:

data = """
552D3AE5|HellothisIsATest__**wordIWant**|someotherstuff|0
3685248S|HellomynameIsAlex__**wordIWant2**|someotherstuff|0
8963252A|HelloiAm25YearsOld__**wordIWant3**|someotherstuff|0
""".strip().splitlines()

for line in data:
    chunks = line.split("|")
    bits = chunks[1].split('__')
    print(line, bits[1])

输出

552D3AE5|HellothisIsATest__**wordIWant**|someotherstuff|0 **wordIWant**
3685248S|HellomynameIsAlex__**wordIWant2**|someotherstuff|0 **wordIWant2**
8963252A|HelloiAm25YearsOld__**wordIWant3**|someotherstuff|0 **wordIWant3**

如果数据始终采用该格式,并且假设每行都是不同的字符串,则可以使用:

import re

strings = [
    "552D3AE5|HellothisIsATest__wordIWant|someotherstuff|0", 
    "3685248S|HellomynameIsAlex__wordIWant2|someotherstuff|0",
    "8963252A|HelloiAm25YearsOld__wordIWant3|someotherstuff|0"
]

for st in strings:
    word_i_want = re.match(r'__([^|]*)', st).group(1)

这将在每个字符串中搜索两个下划线,然后搜索所有内容,直到找到一个垂直条为止。group(0)将是整个匹配,包括下划线,而group(1)只是wordIWant,因为我们将其括在括号中。你知道吗

编辑: 如果您的字符串只是一个大的块,则可以使用以下命令:

import re
big_string = 
"""552D3AE5|HellothisIsATest__wordIWant|someotherstuff|0
3685248S|HellomynameIsAlex__wordIWant2|someotherstuff|0
8963252A|HelloiAm25YearsOld__wordIWant3|someotherstuff|0"""

words_i_want = re.findall(r'__([^|]*)', big_string)

在本例中,words_i_want将是所需单词的列表。你知道吗

相关问题 更多 >

    热门问题