Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除文本中的相关连字符_Python_Python 2.7 - Fatal编程技术网

Python 删除文本中的相关连字符

Python 删除文本中的相关连字符,python,python-2.7,Python,Python 2.7,假设我有这样的文本: a=“我倾向于问简单的问题” 我想首先提取连字符的单词,即首先确定文本中是否存在连字符,这很容易。例如,我使用re.match(“\s*-\s*”,a)检查句子是否有连字符 1) 接下来,我想提取前面和后面的部分单词(在本例中,我想提取“斜面”和“ed”) 2) 接下来,我想把它们合并成“倾斜”并打印所有这些单词 我被困在第一步。请帮忙 >>> import re >>> a = "I am inclin- ed to ask simpl

假设我有这样的文本:

a=“我倾向于问简单的问题”

我想首先提取连字符的单词,即首先确定文本中是否存在连字符,这很容易。例如,我使用re.match(“\s*-\s*”,a)检查句子是否有连字符

1) 接下来,我想提取前面和后面的部分单词(在本例中,我想提取“斜面”和“ed”)

2) 接下来,我想把它们合并成“倾斜”并打印所有这些单词

我被困在第一步。请帮忙

>>> import re
>>> a = "I am inclin- ed to ask simple questions"
>>> result = re.findall('([a-zA-Z]+-)\s+(\w+)', a)
>>> result
[('inclin-', 'ed')]

>>> [first.rstrip('-') + second for first, second in result]
['inclined']
或者,您可以让第一组保存单词,而不带尾随的
-

>>> result = re.findall('([a-zA-Z]+)-\s+(\w+)', a)
>>> result
[('inclin', 'ed')]
>>> [''.join(item) for item in result]
['inclined']
这也适用于字符串中的多个匹配项:

>>> a = "I am inclin- ed to ask simp- le quest- ions"
>>> result = re.findall('([a-zA-Z]+)-\s+(\w+)', a)
>>> [''.join(item) for item in result]
['inclined', 'simple', 'questions']

试试你的正则表达式,它应该适合你:

a = "I am inclin- ed to ask simple questions"

try:
    m = re.search('\S*\-(.|\s)\S*', a) #this will get the whole word, i.e "inclin- ed"
except AttributeError:
    #not found in a

print m

然后你剥去你的字符串,把它们作为一个数组抓取。

我认为re.findall('([a-zA-Z]+)\s*-\s*(\w+),a)更好地抓住了这个问题。关于正则表达式,你可以写很多方法来做一件事,所以无论对你来说是什么,我只是想也许你会有一个撇号或特殊的字符。但我希望这有帮助。