在Python中如何分隔字符串中的标点符号?

2024-09-30 10:28:54 发布

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

我基本上是解析文件中的数据。在我的代码中,我会根据空格字符分割文件的每一行-->;结构分裂(" "). 我需要的是一种分离出字符串中可能出现的标点符号的方法。在

当我说puncutation时,我指的是

import string
print (string.punctuation)

谢谢!在


Tags: 文件数据方法字符串代码importgtstring
2条回答

坚持原著会更容易些,不是吗?你把标点符号放回去的最终目标是什么?如果你要重建整条生产线,为什么不把它放在第一位呢?在

pattern = '['+''.join(string.punctuation)+']+' # Make a char set in regex syntax

for line in file:
    tokens = line.split(' ')
    for token in tokens:
        parsed = parse_token(re.sub(pattern, token))
        # Now do whatever else you might need to do with token and parsed.
    # Remember, you still have access to the `line` string and `tokens` list!

def parse_token(token):
    pass # Do whatever you need to do with your "clean" token here.

我会使用正则表达式来实现:

>>> re.split(r'(\W)', 'This is a sentence. This is another sentence.')
    ['This',
 ' ',
 'is',
 ' ',
 'a',
 ' ',
 'sentence',
 '.',
 '',
 ' ',
 'This',
 ' ',
 'is',
 ' ',
 'another',
 ' ',
 'sentence',
 '.',
 '']

您可以遍历结果列表,更改单词,然后''.join()将其还原为一个在相同位置使用相同标点符号的句子。在

相关问题 更多 >

    热门问题