[英]How to remove a substring that starts and ends with certain characters in Python
[英]Email extraction starts and ends with unwanted characters (python)
所以我有一个程序可以提取电子邮件和电话号码。 我跑了,电话号码很好。 但是,这些电子邮件将继续导致:例如:3465Usjohnson@astate.eduUProvost而不是sjohnson@astate.edu正在从中提取的环绕文本:870-972-3465Usjohnson@astate.eduUProvost和副总理博士。 Lynita Cooksey870-972-2 030 870-972-2036Ulcooksey@astate.edu
在实际的PDF中,有白色和空白,但是在复制和粘贴时,它们之间没有空格,因此也没有我收到的电子邮件。(看起来像是: 在此处输入图片说明
#! python 3
import re, pyperclip
# Regex for phone numbers
phoneRegex = re.compile(r'''
# 860-555-3951, 555-3951, (860) 555-3951, 555-3951 ext 12345, ext. 12345, x12345
(
((\d\d\d)|(\(\d\d\d\)))? #area code (optional)
(\s|-) #first seperator
\d\d\d #first 3 digits
- #second seperator
\d\d\d\d #last 4 digits
(((ext(\.)?\s)|x) #Extension-words (optional)
(\d{2,5}))? #Extension - numbers (optional)
)
''', re.VERBOSE)
#Regex for Emails
emailRegex = re.compile(r'''
#some._+thing@(/d{2,5}))?.com
[a-zA-Z0-9_.+]+ #Name part
@ #@ symbol
[a-zA-Z0-9_.+]+ #domain
''', re.VERBOSE)
#pyperclip get text off
text = pyperclip.paste()
#extract
extractedPhone = phoneRegex.findall(text)
extractedEmail = emailRegex.findall(text)
allPhoneNumbers = []
for phoneNumber in extractedPhone:
allPhoneNumbers.append(phoneNumber[0])
#copy to clipboard
results = '\n'.join(allPhoneNumbers) + '\n'.join(extractedEmail)
pyperclip.copy(results)
因为我没有原始文本,所以我将使用您示例中的字符串。
看看以下两个正则表达式是否适合您。 我还包括一个更精确的三分之一。
'(?<=\\dU)[\\w]+@[\\w\\.]+?(?=U|\\s|$)'
。
'(?<=\\dU)[\\w]+@[\\w]+\\.[\\w]+?(?=U|\\s|$)'
。
示例测试
>>> import re
>>> string = '''3465Usjohnson@astate.eduUProvost instead of sjohnson@astate.edu The surround text that it is being extracted from: 870-972-3465Usjohnson@astate.eduUProvost and Vice ChancellorDr. Lynita Cooksey870-972-2 030 870-972-2036Ulcooksey@astate.edu'''
>>> re.findall('(?<=\dU)[\w]+@[\w\.]+?(?=U|\s|$)', string)
#Output
['sjohnson@astate.edu', 'sjohnson@astate.edu', 'lcooksey@astate.edu']
>>> re.findall('(?<=\dU)[\w]+@[\w]+\.[\w]+?(?=U|\s|$)', string)
#Output
['sjohnson@astate.edu', 'sjohnson@astate.edu', 'lcooksey@astate.edu']
。
更准确一点,因为电子邮件都以.edu
'(?<=\\dU)[\\w]+@[\\w]*\\.edu(?=U|\\s|$)'
。
示例测试
>>> string = '''3465Usjohnson@astate.eduUProvost instead of sjohnson@astate.edu The surround text that it is being extracted from: 870-972-3465Usjohnson@astate.eduUProvost and Vice ChancellorDr. Lynita Cooksey870-972-2 030 870-972-2036Ulcooksey@astate.edu'''
>>> re.findall('(?<=\dU)[\w]+@[\w]*\.edu(?=U|\s|$)', string)
#Output
['sjohnson@astate.edu', 'sjohnson@astate.edu', 'lcooksey@astate.edu']
我自己是Python新手。 如果文本是从' astate.edu '网站专门提取的,我想你可以使用这个正则表达式:
text='70-972-3465Usjohnson@astate.eduUProvost and Vice ChancellorDr. Lynita Cooksey870-972-2 030 870-972-2036Ulcooksey@astate.edu'
import re
email= re.findall('[a-z]+\@\w+\.edu',text)
#output
['sjohnson@astate.edu', 'lcooksey@astate.edu']
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.