我想从此字符串中删除多余的r和n。我试过正则表达式。不知道正则表达式或其他方法是否会对您有所帮助。
这是我试图使用import re的代码
text = "r n r n r nFamily Medical History new r n r n r r r Roger nRobert n nDawson n49 nyears old , right shoulder"
regex_pattern = re.compile(r'\s[rn]\s')
matches = regex_pattern.findall(text)
for match in matches:
text = text.replace(match," ")
print(text)
电流输出:
r nFamily Medical History new Roger nRobert nDawson n49 nyears old , right shoulder
我们仍然看到很多r n。还想知道如何从n49,nyears中删除'n'并从道森中删除第一个'n'而又不删除最后一个'n'
预期产量:
Family Medical History new Roger Robert Dawson 49 years old , right shoulder
我在这里建议使用一种NLP方法,因为我看不到正则表达式如何nyears
从new
(正确的拼写)中分辨出(错误的拼写)。
首先,删除所有独立的r
/n
以及粘在大写单词和数字上的那些,然后拆分字符串并检查以拼写检查器开头n
或r
以拼写检查器开头的每个单词。n
如果word[1:]
正确,word
则可以删除第一个。如果两者都不正确,我认为可以退回到word
。
例如,要运行拼写检查,您可以使用TextBlob
。
这是一个Python代码演示:
from textblob import TextBlob
from textblob import Word
import re
s = "r n r n r nFamily Medical History new r n r n r r r Roger nRobert n nDawson n49 nyears old , right shoulder"
s = re.sub(r'\b[rn](?=[A-Z0-9\s]|$)', '', s)
result = []
for w in s.split():
if not w.startswith(('n','r')): # The w word does not start with n or r...
result.append(w) # Add it to the result
else:
if Word(w).correct() == w: # If w is a correct word
result.append(w) # Add it to the result
else:
if Word(w[1:]).correct() == w[1:]: # If w[1:] is correct
result.append(w[1:]) # Add w[1:] to the result
else:
result.append(w) # Fallback: add w to the result
print(" ".join(result))
# => Family Medical History new Roger Robert Dawson 49 years old , right shoulder
如果立即紧随大写字母,数字或字符串结尾,则re.sub(r'\b[rn](?=[A-Z0-9\s]|$)', '', s)
删除该部分r
并n
在单词开头。
然后,for w in s.split():
迭代句子中的单词,仅在以n
或开头且r
拼写错误为的情况下替换单词w[1:]
。
免责声明:TextBlob
仅作为示例。您可以自由使用任何其他拼写检查库。TextBlob拼写检查“基于模式库中实现的Peter Norvig的“如何编写拼写校正器” 1。准确度约为70% ”
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句