2016-06-24 4 views
2

이 질문은 실제로 자체적으로 말하지만 문제는 nltk로 문자열의 색상을 식별 할 수 있기를 원하며 찾을 수있는 부분은 품사를 분류하는 방법입니다. 나는 내가 지원하고자하는 모든 색상의 목록을 만들 수 있다는 것을 알고 있지만 CSS에서 사용할 수있는 모든 색상을 지원하고자하므로 청록색과 아쿠아 마린과 같이 이상한 목록이 많이있을 것입니다. 이것을 모두 작성하는 것보다 간단한 방법이 있다면 크게 도움이 될 것입니다. 감사!파이썬에서 nltk로 문자열의 색상을 식별하는 방법은 무엇입니까?

편집 :이 음성 인식에 사용의

그것은 내가 처음 내가 함께 자연 언어 대신 실행처럼 밖으로 간격 색상 이름이 필요 내 질문을 할 때 언급하는 것을 잊었다 것으로 보인다 인해. 그러므로 나는 원래 질문에 아주 잘 대답하기 때문에 "Tadhg McDonald-Jensen"의 대답을 최고로 선택했습니다. 그러나 나는 또한 공백으로 색 이름을 제공하는 내 자신의 대답을 게시했습니다. 희망이 도움이!

답변

2

당신은 단지 webcolors.CSS3_NAMES_TO_HEX의 회원 확인이 인식하는 모든 CSS 색상 이름을 얻을 수 the webcolors package을 사용할 수 있습니다 :이 webcolors.CSS3_NAMES_TO_HEX.keys() 당신에게 python3에 설정된 python2 또는 dictkeys의 목록을 제공한다는 것을 의미

>>> import webcolors 
>>> "green" in webcolors.CSS3_NAMES_TO_HEX 
True 
>>> "deepskyblue" in webcolors.CSS3_NAMES_TO_HEX 
True 
>>> "aquamarine" in webcolors.CSS3_NAMES_TO_HEX 
True 
>>> len(webcolors.CSS3_NAMES_TO_HEX) 
147 

모든 CSS3 색상 이름 중. (어쨌든 나를 위해)

1

나는 nltk를 사용하지 않고 정규식을 사용합니다.

  1. 모든 CSS 색상의 목록을 가져옵니다 (here)
  2. 가 색상 이름을 추출하고
  3. 당신이 원하는 것을 일치하는 정규식 패턴
  4. 사용이 정규식 패턴을 구축 (사용 BeautifulSoup로) 목록을 작성 당신의 문자열에


(방금이 개 마지막 라인과 필요한 경우 프록시 설정을 변경해야합니다)

에 대한이 작품
from bs4 import BeautifulSoup 

color_url = 'http://colours.neilorangepeel.com/' 
proxies = {'http': 'http://proxy.foobar.fr:3128'}#if needed 

#GET THE HTML FILE 
import urllib.request 
authinfo = urllib.request.HTTPBasicAuthHandler()# set up authentication info 
proxy_support = urllib.request.ProxyHandler(proxies) 
opener = urllib.request.build_opener(proxy_support, authinfo, 
            urllib.request.CacheFTPHandler)# build a new opener that adds authentication and caching FTP handlers 
urllib.request.install_opener(opener)# install the opener 
colorfile = urllib.request.urlopen(color_url) 

soup = BeautifulSoup(colorfile, 'html.parser') 

#BUILD THE REGEX PATERN 
colors = soup.find_all('h1') 
colorsnames = [color.string for color in colors] 
colorspattern = '|'.join(colorsnames) 
colorregex = re.compile(colorspattern) 

#MATCH WHAT YOU NEED 
if colorregex.search(yourstring): 
    do what you want 
2

솔루션 :

참고 : 단순히 공백없이 색상을해야하는 경우가 (대신 '깊은 하늘 블루'의 'deepskyblue') 이전의 대답 중 하나가 작동합니다 . 그러나, 나는 음성 인식과 함께이를 사용하고 있기 때문에 나는 더 완전한으로 볼 (파이썬 3) 다음 코드를 사용하여 달성 할 수있는 자연 언어로 공백으로 구분 색상이 필요 :

을 당신이

print(getColors()) 

을 실행하면 다음

import urllib.request 
from bs4 import BeautifulSoup 

def getColors(): 
    html = urllib.request.urlopen('http://www.w3schools.com/colors/colors_names.asp').read() 
    soup = BeautifulSoup(html, 'html.parser') 
    children = [item.findChildren() for item in soup.find_all('tr')] 
    colors = [''.join(' '+x if 'A' <= x <= 'Z' else x for x in item[0].text.replace(u'\xa0', '')).strip().lower() for item in children] 
    return colors[1:] 

당신이 얻을 :

['alice blue', 'antique white', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanched almond', 'blue', 'blue violet', 'brown', 'burly wood', 'cadet blue', 'chartreuse', 'chocolate', 'coral', 'cornflower blue', 'cornsilk', 'crimson', 'cyan', 'dark blue', 'dark cyan', 'dark golden rod', 'dark gray', 'dark grey', 'dark green', 'dark khaki', 'dark magenta', 'dark olive green', 'dark orange', 'dark orchid', 'dark red', 'dark salmon', 'dark sea green', 'dark slate blue', 'dark slate gray', 'dark slate grey', 'dark turquoise', 'dark violet', 'deep pink', 'deep sky blue', 'dim gray', 'dim grey', 'dodger blue', 'fire brick', 'floral white', 'forest green', 'fuchsia', 'gainsboro', 'ghost white', 'gold', 'golden rod', 'gray', 'grey', 'green', 'green yellow', 'honey dew', 'hot pink', 'indian red', 'indigo', 'ivory', 'khaki', 'lavender', 'lavender blush', 'lawn green', 'lemon chiffon', 'light blue', 'light coral', 'light cyan', 'light golden rod yellow', 'light gray', 'light grey', 'light green', 'light pink', 'light salmon', 'light sea green', 'light sky blue', 'light slate gray', 'light slate grey', 'light steel blue', 'light yellow', 'lime', 'lime green', 'linen', 'magenta', 'maroon', 'medium aqua marine', 'medium blue', 'medium orchid', 'medium purple', 'medium sea green', 'medium slate blue', 'medium spring green', 'medium turquoise', 'medium violet red', 'midnight blue', 'mint cream', 'misty rose', 'moccasin', 'navajo white', 'navy', 'old lace', 'olive', 'olive drab', 'orange', 'orange red', 'orchid', 'pale golden rod', 'pale green', 'pale turquoise', 'pale violet red', 'papaya whip', 'peach puff', 'peru', 'pink', 'plum', 'powder blue', 'purple', 'rebecca purple', 'red', 'rosy brown', 'royal blue', 'saddle brown', 'salmon', 'sandy brown', 'sea green', 'sea shell', 'sienna', 'silver', 'sky blue', 'slate blue', 'slate gray', 'slate grey', 'snow', 'spring green', 'steel blue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'white smoke', 'yellow', 'yellow green'] 

희망이 도움이됩니다!

+0

사용하는 솔루션이 아닌 경우 왜 내 대답을 수락 했습니까?담당자에게 감사하지만, 원하는대로하지 않으면 "받아 들일 수있는 대답입니다"라고 생각하지 않습니다. –

+1

내가 음성 인식과 함께 사용하고자하는 것과 같은 세부 사항을 빠뜨린 내 원래 질문에 대답했기 때문에 받아 들였습니다. 또한 같은 줄을 따라 질문에 답하기 때문에 다른 사람들은 단순히 색상을 원할뿐 아니라 공백없이 CSS에있는 방식으로 알고 싶어합니다. 그래서 대부분 다른 사람에게 도움이되기 때문에 나에게 비슷한 것을하고있는 사람들은 내 게시물을 볼 수도 있습니다. 왜냐하면 저는 여기에서 알았 기 때문에 무엇을해야할지 잘 모르기 때문입니다. – TimTheEnchanter

+0

P. 너는 분명히 내가 여기있는 것보다 훨씬 더 많이 했어. 내가 바꿔야한다고 생각하면 행복 할거야. 감사! – TimTheEnchanter

관련 문제