Programming

문자열을 목록으로 나누는 방법?

procodes 2020. 2. 10. 22:30
반응형

문자열을 목록으로 나누는 방법?


파이썬 함수가 문장 (입력)을 나누고 각 단어를 목록에 저장하고 싶습니다. 내 현재 코드는 문장을 분할하지만 단어를 목록으로 저장하지 않습니다. 어떻게해야합니까?

def split_line(text):

    # split the text
    words = text.split()

    # for each word in the line:
    for word in words:

        # print the word
        print(words)

text.split()

각 단어를 목록에 저장하기에 충분해야합니다. words이미 문장의 단어 목록이므로 루프가 필요하지 않습니다.

둘째, 오타 일 수도 있지만 루프가 약간 엉망입니다. 실제로 append를 사용하고 싶다면 다음과 같습니다.

words.append(word)

아니

word.append(words)

text연속 된 공백 행 에서 문자열을 분할합니다 .

words = text.split()      

text구분 기호 에서 문자열을 분할하십시오 ",".

words = text.split(",")   

단어 변수는 a가 list되고 text분리 문자 에서 분리 된 단어가 포함 됩니다.


str.split ()

sep를 구분 기호로 사용하여 문자열 의 단어 목록을 반환합니다. sep가 지정되지 않거나 None 인 경우 다른 분할 알고리즘이 적용됩니다. 연속 공백 실행은 단일 구분 기호로 간주되며 결과에는 다음이 포함됩니다. 문자열에 선행 또는 후행 공백이 있으면 시작 또는 끝에 빈 문자열이 없습니다.

>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>> 

목록으로 한 문장으로 무엇을하려고하는지에 따라 Natural Language Took Kit 를 볼 수 있습니다 . 텍스트 처리 및 평가를 많이 처리합니다. 이를 사용하여 문제를 해결할 수도 있습니다.

import nltk
words = nltk.word_tokenize(raw_sentence)

이것은 구두점을 나누는 이점이 있습니다.

예:

>>> import nltk
>>> s = "The fox's foot grazed the sleeping dog, waking it."
>>> words = nltk.word_tokenize(s)
>>> words
['The', 'fox', "'s", 'foot', 'grazed', 'the', 'sleeping', 'dog', ',', 
'waking', 'it', '.']

이를 통해 원하지 않는 구두점을 걸러 내고 단어 만 사용할 수 있습니다.

string.split()문장의 복잡한 조작을 계획하지 않으면 다른 솔루션을 사용 하는 것이 좋습니다.

[편집]


이 알고리즘은 어떻습니까? 공백으로 텍스트를 분할 한 다음 문장 부호를 자릅니다. 이렇게하면와 같은 단어 내부의 어포 스트로피를 손상시키지 않으면 서 단어의 가장자리에서 구두점을 조심스럽게 제거합니다 we're.

>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"

>>> text.split()
["'Oh,", 'you', "can't", 'help', "that,'", 'said', 'the', 'Cat:', "'we're", 'all', 'mad', 'here.', "I'm", 'mad.', "You're", "mad.'"]

>>> import string
>>> [word.strip(string.punctuation) for word in text.split()]
['Oh', 'you', "can't", 'help', 'that', 'said', 'the', 'Cat', "we're", 'all', 'mad', 'here', "I'm", 'mad', "You're", 'mad']

파이썬 함수가 문장 (입력)을 나누고 각 단어를 목록에 저장하고 싶습니다.

str().split()방법은 문자열을 가져 와서 목록으로 나눕니다.

>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0

당신이 겪고있는 문제는 오타 때문 print(words)입니다 print(word).

word변수 이름을로 바꾸면 다음 current_word과 같습니다.

def split_line(text):
    words = text.split()
    for current_word in words:
        print(words)

..해야 할 때 :

def split_line(text):
    words = text.split()
    for current_word in words:
        print(current_word)

어떤 이유로 for 루프에서 목록을 수동으로 구성하려면 append()모든 단어를 소문자로 만들고 싶기 때문에 list 메서드를 사용합니다 .

my_list = [] # make empty list
for current_word in words:
    my_list.append(current_word.lower())

또는 목록 이해력을 사용하여 조금 더 깔끔합니다 .

my_list = [current_word.lower() for current_word in words]

shlex 에는 .split()기능이 있습니다. str.split()따옴표를 유지하지 않고 따옴표로 묶은 문구를 단일 단어로 취급한다는 점과 다릅니다 .

>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']

단어 / 문장 을 모두 목록에 넣으려면 다음과 같이하십시오.

print(list("word"))
#  ['w', 'o', 'r', 'd']


print(list("some sentence"))
#  ['s', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

오타 때문에 혼란 스럽다고 생각합니다.

교체 print(words)print(word)루프 내부의 모든 단어는 다른 줄에 인쇄 한합니다

참고 URL : https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list



반응형