2016-06-08 99 views
1

我只有一個月進入python,這個基本的練習讓我走上了牆。我正在嘗試製作一個搜索腳本,用於搜索我輸入的文本並將結果放在剪貼板上。我被困在下面約一個星期。如果我直接從站點複製文本並輸入它,沒有結果(我得到一個None輸出)。但如果我直接複製數字,沒有問題,它完美地讀取它們。我已經嘗試了幾種方法(如下所示),沒有運氣,它讓我難住了。下面是我粘貼的示例文本,它沒有給出結果:正則表達式返回無(python)

Dr。有人垃圾郵件

房:BLD-2001

+353(0)11 123456

任何輸入的人可以提供將是巨大的。另外一個側面的問題,任何有關學習python的書籍/建議都會很棒。目前在「使用python自動化無聊的東西」。只是爲了好玩。提前致謝。

import re, pyperclip 

def findphone(numbers): 
    numregex = re.compile(r'\(\d\)\d\d\s\d+') 
    numregex1 = re.compile(r'(0)11 123456') 
    phoneRegex = re.compile(r'''(
    (\+\d{3})?     # area code 
    (\s|-|\.)?     # separator 
    (\d{3}|\(\d\)\d\d)?   # area code 
    (\s|-|\.)?     # separator 
    \d{6}       # Landline Number 
    )''', re.VERBOSE) 
    mo = numregex.search(numbers) 
    mo0 = numregex1.search(numbers) 
    mo1 = phoneRegex.search(numbers) 
    print('mo ' +str(mo)) 
    print('mo0 ' +str(mo0)) 
    print('mo1 ' +str(mo1)) 

print('Input check text') 
numbers = input() 
findphone(numbers) 
+0

我不「直接從一個網站,並輸入它複製文本」與理解之間的區別「直接在號碼拷貝。」另外,你可能會發現這很有用:https://regex101.com/#python –

+1

對不起約翰,沒有在這一行中正確解釋自己。練習的目標是輸入一個大字符串,對它進行排序,並使用pyperclip將結果輸出到剪貼板。艾倫下面讓我走上了良好的軌道。我正在用你給我發送的正則表達式鏈接解構他的編輯,讓我充分了解它。太感謝了! – David

回答

1

看到改變直列

# -*- coding: utf-8 -*- 
# 1. added above line 
import re 

def findphone(numbers): 
    numregex = re.compile(r'(\(\d\)\d\d\s\d+)') # 2. Added circular brackets around the regular expression 
    numregex1 = re.compile(r'(\(0\)11 123456)') # 3. Escaped circular brackets around 0 

    # 4. Made small changes to the following, mainly changing brackets. 
    phoneRegex = re.compile(r''' 
    (\+\d{3})     # area code 
    [\s|-|\.]      # separator 
    (\d{3}|\(\d\)\d\d)?   # area code 
    [\s|-|\.]      # separator 
    (\d{6})       # Landline Number 
    ''', re.VERBOSE) 
    mo = numregex.search(numbers) 
    mo0 = numregex1.search(numbers) 
    mo1 = phoneRegex.search(numbers) 
    if mo: 
     print('mo ' +str(mo.groups())) 
    if mo0: 
     print('mo0 ' +str(mo0.groups())) 
    if mo1: 
     # 5. break down in separate variables 
     country_code = mo1.groups()[0] 
     area_code = mo1.groups()[1] 
     landline = mo1.groups()[2] 
     print country_code, area_code, landline 

print('Input check text') 
findphone("‌Dr. Someone Spam\nRoom: BLD-2001\n+353 (0)11 123456") 
+0

切換到一個字符類是好的,但要擺脫管道:'[\ s .-]'。另外,您可以使用'group()'返回整個匹配,並且可以使用group(1),group(2)等來返回組。更加整潔,你正在用'groups()'做什麼。 –

+0

謝謝Alan,我感謝你所做的編輯的幫助和詳細分解,對像我這樣的初學者有着巨大的幫助! – David