문제 설명
python 태그에서 단어와 숫자 나누기 (Split words and numbers from tags python)
나는 "Am/VI/NN good/Adj 충분히/Prep for/Prep 1/2/NUM"이라는 문장을 가지고 있으며 단어와 태그로 분할하고 단어와 태그에 대한 두 개의 다른 사전을 만들어야 합니다. 여기에서 스레드를 보았지만 이것을 1/2/NUM로 나누는 것에 대한 단어가 없었습니다.
그래서 다음과 같이 해야 한다고 생각합니다.
s = "Am/V I/NN good/Prep enough/Prep for/Prep 1/2/NUM"
sent = s.split()
for word in sent:
word = word.split('/[a‑z]')
dict_of_words = list(words[0])
doct_of_tags = list(words[1])
하지만 그러면 다음과 같이 표시됩니다.
['Am/'V]
['I/NN']
[good/Prep]
etc.
이 문제를 어떻게 해결합니까?
참조 솔루션
방법 1:
split
on the spaces first:
s = "Am/V I/NN good/Prep enough/Prep for/Prep 1/2/NUM"
sent = s.split()
Then for each item rsplit
on the /
character:
for item in sent:
data = item.rsplit('/', 1)
word = data[0]
tag = data[1]
Or if you prefer more concise code:
for item in sent:
word, tag = item.rsplit('/', 1)
방법 2:
As noted in the comments on shuttle87's answer, here is a simple example showing split with regex in case you need to split on multiple characters, which you can't do with the string split method.
import re
s = "Am/V I/NN good/Prep enough/Prep for/Prep 1/2/NUM"
parts = s.split(" ")
words_tags = [re.split(r'/(?=[A‑Za‑z])', part) for part in parts]
words = []
tags = []
for word_tag in words_tags:
words.append(word_tag[0])
tags.append(word_tag[1])
['Am', 'I', 'good', 'enough', 'for', '1/2'] ['V', 'NN', 'Prep', 'Prep', 'Prep', 'NUM']
(by Repzz、shuttle87、binarysubstrate)