簡體   English   中英

如何將字符串拆分為單詞列表?

[英]How do I split a string into a list of words?

如何拆分句子並將每個單詞存儲在列表中? 例如,給定一個像"these are words"這樣的字符串,我如何得到一個像["these", "are", "words"]這樣的列表?

給定一個字符串sentence ,它將每個單詞存儲在一個名為words的列表中:

words = sentence.split()

要在任何連續運行的空格上拆分字符串text

words = text.split()      

要在自定義分隔符上拆分字符串text ,例如","

words = text.split(",")   

words變量將是一個list ,並包含分隔符上拆分的text中的單詞。

使用str.split()

返回字符串中的單詞列表,使用 sep 作為分隔符...如果未指定 sep 或為 None,則應用不同的拆分算法:連續空格的運行被視為單個分隔符,結果將包含如果字符串具有前導或尾隨空格,則在開頭或結尾處沒有空字符串。

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

根據您計划對句子列表執行的操作,您可能需要查看Natural Language Take 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']

我希望我的 python 函數拆分一個句子(輸入)並將每個單詞存儲在一個列表中

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 循環中手動構造一個列表,您將使用 list append()方法,可能是因為您想將所有單詞小寫(例如):

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

或者更簡潔一些,使用list-comprehension

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

如果您想要列表中的單詞/句子的所有字符,請執行以下操作:

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


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

shlex有一個.split()函數。 它與str.split()的不同之處在於它不保留引號並將引用的短語視為單個單詞:

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

注意:它適用於類 Unix 命令行字符串。 它不適用於自然語言處理。

我認為你因為錯字而感到困惑。

在循環中將print(words)替換為print(word)以將每個單詞打印在不同的行上

在不損害單詞內部撇號的情況下拆分單詞 請找到 input_1 和 input_2 摩爾定律

def split_into_words(line):
    import re
    word_regex_improved = r"(\w[\w']*\w|\w)"
    word_matcher = re.compile(word_regex_improved)
    return word_matcher.findall(line)

#Example 1

input_1 = "computational power (see Moore's law) and "
split_into_words(input_1)

# output 
['computational', 'power', 'see', "Moore's", 'law', 'and']

#Example 2

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

split_into_words(input_2)
#output
['Oh',
 'you',
 "can't",
 'help',
 'that',
 'said',
 'the',
 'Cat',
 "we're",
 'all',
 'mad',
 'here',
 "I'm",
 'mad',
 "You're",
 'mad']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM