2008-12-14 65 views
38

我试图将字符串拆分为单词和标点符号,将标点符号添加到拆分生成的列表中。将字符串拆分为单词和标点符号

例如:

>>> c = "help, me" 
>>> print c.split() 
['help,', 'me'] 

我真正想要列表样子是:

['help', ',', 'me'] 

所以,我想在从单词的标点符号分裂空白字符串分割。

我试着先分析字符串,然后再运行分裂:

>>> for character in c: 
...  if character in ".,;!?": 
...    outputCharacter = " %s" % character 
...  else: 
...    outputCharacter = character 
...  separatedPunctuation += outputCharacter 
>>> print separatedPunctuation 
help , me 
>>> print separatedPunctuation.split() 
['help', ',', 'me'] 

这将产生我想要的结果,但对大文件非常缓慢。

有没有办法更有效地做到这一点?

+0

对于本例(不是一般情况)`c.replace('','')。partition(',')` – 2016-11-21 08:59:51

回答

57

这是或多或少地做到这一点:

>>> import re 
>>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!") 
['Hello', ',', "I'm", 'a', 'string', '!'] 

的诀窍是,不要去想哪里拆分字符串,但在标记中包含的内容。

注意事项:

  • 下划线(_)被认为是一内单词字符。替换\ w,如果你不想要的话。
  • 这不适用于字符串中的(单个)引号。
  • 在正则表达式的右半部分放置任何想要使用的标点符号。
  • 在re中没有明确提到的任何内容都被默默地抛弃了。
-1

您是否尝试过使用正则表达式?

http://docs.python.org/library/re.html#re-syntax


顺便说。为什么你需要第二个“,”?你会知道每个文本写入之后即

[0]

“”

[1]

“”

所以,如果你想添加的“ ,“当你使用数组时,你可以在每次迭代后执行它。

4

在Perl风格的正则表达式语法中,\b匹配单词边界。这对于执行基于正则表达式的拆分应该很方便。

编辑:我已经被hop通知,“空匹配”在Python的re模块的分割函数中不起作用。我将这里留下来作为任何人被这个“功能”难住的信息。

+0

只有它不会因为re.split不能与r'\ b'一起工作... – hop 2008-12-15 01:09:10

+0

这到底是什么?这是re.split中的错误吗?在Perl中,`split/\ b \ s * /`没有任何问题。 – Svante 2008-12-15 01:29:34

+0

这是一种文件记录,re.split()不会分裂空的匹配......所以,不,不/一个/一个错误。 – hop 2008-12-15 01:51:26

0

我想你可以在NLTK找到所有你可以想象的帮助,特别是因为你使用的是python。本教程对此问题进行了全面的讨论。

1

以下是对您的实施进行的较小更新。如果你试图做更详细的事情,我建议你看看dorfier建议的NLTK。

这可能会稍微快一点,因为使用''.join()代替+ =,即known to be faster

import string 

d = "Hello, I'm a string!" 

result = [] 
word = '' 

for char in d: 
    if char not in string.whitespace: 
     if char not in string.ascii_letters + "'": 
      if word: 
        result.append(word) 
      result.append(char) 
      word = '' 
     else: 
      word = ''.join([word,char]) 

    else: 
     if word: 
      result.append(word) 
      word = '' 
print result 
['Hello', ',', "I'm", 'a', 'string', '!'] 
2

这是我的项目。

我对我的怀疑在于效率如何,或者它是否抓住了所有情况(注意“!!!”分组在一起;这可能会或可能不会是件好事)。

>>> import re 
>>> import string 
>>> s = "Helo, my name is Joe! and i live!!! in a button; factory:" 
>>> l = [item for item in map(string.strip, re.split("(\W+)", s)) if len(item) > 0] 
>>> l 
['Helo', ',', 'my', 'name', 'is', 'Joe', '!', 'and', 'i', 'live', '!!!', 'in', 'a', 'button', ';', 'factory', ':'] 
>>> 

一个明显的优化将编译前手(使用re.compile)如果你要一行一行地基础上做此正则表达式。

22

这里是一个Unicode的版本:

re.findall(r"\w+|[^\w\s]", text, re.UNICODE) 

第一替代捕获的单词的字符序列(如由unicode的定义,因此“RESUME”不会变成['r', 'sum']);第二个捕获单个非单词字符,忽略空白。

请注意,与顶级答案不同,此处将单引号视为单独的标点符号(例如“我是” - >['I', "'", 'm'])。这似乎是NLP的标准,所以我认为它是一个功能。

0

我想出了一个办法来标记使用\b它不需要硬编码的所有文字和\W+模式:

>>> import re 
>>> sentence = 'Hello, world!' 
>>> tokens = [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', sentence)] 
['Hello', ',', 'world', '!'] 

这里.*?\S.*?是匹配任何一个模式是不是一个空间和$被添加到如果它是标点符号,则匹配字符串中的最后一个标记。

不过要注意以下 - 这组标点符号由多于一个符号:

>>> print [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', '"Oh no", she said')] 
['Oh', 'no', '",', 'she', 'said'] 

当然,你可以找到与分割这样的群体:

>>> for token in [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', '"You can", she said')]: 
...  print re.findall(r'(?:\w+|\W)', token) 

['You'] 
['can'] 
['"', ','] 
['she'] 
['said'] 
0

试试这个:

string_big = "One of Python's coolest features is the string format operator This operator is unique to strings" 
my_list =[] 
x = len(string_big) 
poistion_ofspace = 0 
while poistion_ofspace < x: 
    for i in range(poistion_ofspace,x): 
     if string_big[i] == ' ': 
      break 
     else: 
      continue 
    print string_big[poistion_ofspace:(i+1)] 
    my_list.append(string_big[poistion_ofspace:(i+1)]) 
    poistion_ofspace = i+1 

print my_list