Nice programing

문자열을 단어 목록으로 변환?

nicepro 2020. 12. 9. 21:43
반응형

문자열을 단어 목록으로 변환?


파이썬을 사용하여 문자열을 단어 목록으로 변환하려고합니다. 다음과 같은 것을 받고 싶습니다.

string = 'This is a string, with words!'

그런 다음 다음과 같이 변환하십시오.

list = ['This', 'is', 'a', 'string', 'with', 'words']

구두점과 공백이 누락 된 것을 확인하십시오. 이것에 대해 가장 빠른 방법은 무엇입니까?


이 시도:

import re

mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ",  mystr).split()

작동 원리 :

문서에서 :

re.sub(pattern, repl, string, count=0, flags=0)

string에서 패턴의 가장 왼쪽에 겹치지 않는 항목을 교체 repl로 교체하여 얻은 문자열을 반환합니다. 패턴을 찾을 수 없으면 문자열이 변경되지 않고 반환됩니다. repl은 문자열 또는 함수일 수 있습니다.

그래서 우리의 경우 :

패턴은 영숫자가 아닌 문자입니다.

[\ w]는 모든 영숫자 문자를 의미하며 문자 집합 [a-zA-Z0-9_]와 같습니다.

a ~ z, A ~ Z, 0 ~ 9 및 밑줄.

그래서 우리는 영숫자가 아닌 문자와 일치시키고 공백으로 바꿉니다.

그런 다음 split () 문자열을 공백으로 분할하고 목록으로 변환합니다.

그래서 'hello-world'

'안녕하세요'가됩니다

re.sub와 함께

그리고 [ 'hello', 'world']

split () 후

의심이 생기면 알려주세요.


나는 이것이 늦은 응답을 감안할 때이 게시물에 걸려 넘어지는 다른 사람들에게 가장 간단한 방법이라고 생각합니다.

>>> string = 'This is a string, with words!'
>>> string.split()
['This', 'is', 'a', 'string,', 'with', 'words!']

이를 올바르게 수행하는 것은 매우 복잡합니다. 연구를 위해 단어 토큰 화라고합니다. 처음부터 시작하는 것이 아니라 다른 사람들이 한 일을보고 싶다면 NLTK를 살펴 봐야합니다 .

>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second."
>>> sentences = nltk.sent_tokenize(paragraph)
>>> for sentence in sentences:
...     nltk.word_tokenize(sentence)
[u'Hi', u',', u'this', u'is', u'my', u'first', u'sentence', u'.']
[u'And', u'this', u'is', u'my', u'second', u'.']

가장 간단한 방법 :

>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'\w+', string)
['This', 'is', 'a', 'string', 'with', 'words']

string.punctuation완전성을 위해 사용 :

import re
import string
x = re.sub('['+string.punctuation+']', '', s).split()

이것은 줄 바꿈도 처리합니다.


글쎄, 당신은 사용할 수 있습니다

import re
list = re.sub(r'[.!,;?]', ' ', string).split()

string둘 다 list내장 유형의 이름이므로 변수 이름으로 사용하고 싶지 않을 것입니다.


단어에 대한 정규식이 가장 많은 제어를 제공합니다. "I 'm"과 같이 대시 또는 아포스트로피가있는 단어를 처리하는 방법을 신중하게 고려하고 싶을 것입니다.


개인적으로 이것은 제공된 답변보다 약간 더 깨끗하다고 ​​생각합니다

def split_to_words(sentence):
    return list(filter(lambda w: len(w) > 0, re.split('\W+', sentence))) #Use sentence.lower(), if needed

list=mystr.split(" ",mystr.count(" "))

@mtrw의 답변에서 영감을 얻었지만 단어 경계에서만 구두점을 제거하도록 개선되었습니다.

import re
import string

def extract_words(s):
    return [re.sub('^[{0}]+|[{0}]+$'.format(string.punctuation), '', w) for w in s.split()]

>>> str = 'This is a string, with words!'
>>> extract_words(str)
['This', 'is', 'a', 'string', 'with', 'words']

>>> str = '''I'm a custom-built sentence with "tricky" words like https://stackoverflow.com/.'''
>>> extract_words(str)
["I'm", 'a', 'custom-built', 'sentence', 'with', 'tricky', 'words', 'like', 'https://stackoverflow.com']

이것은 정규식을 사용할 수없는 코딩 도전에 대한 나의 시도에서 나온 것입니다.

outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')

아포스트로피의 역할은 흥미로워 보입니다.


이렇게하면 알파벳 밖의 모든 특수 문자를 제거 할 수 있습니다.

def wordsToList(strn):
    L = strn.split()
    cleanL = []
    abc = 'abcdefghijklmnopqrstuvwxyz'
    ABC = abc.upper()
    letters = abc + ABC
    for e in L:
        word = ''
        for c in e:
            if c in letters:
                word += c
        if word != '':
            cleanL.append(word)
    return cleanL

s = 'She loves you, yea yea yea! '
L = wordsToList(s)
print(L)  # ['She', 'loves', 'you', 'yea', 'yea', 'yea']

이것이 빠르거나 최적인지 아니면 올바른 프로그래밍 방법인지 확실하지 않습니다.


시도해 볼 수 있습니다.

tryTrans = string.maketrans(",!", "  ")
str = "This is a string, with words!"
str = str.translate(tryTrans)
listOfWords = str.split()

참고 URL : https://stackoverflow.com/questions/6181763/converting-a-string-to-a-list-of-words

반응형