将字符串转换为单词列表?
- 2025-02-20 09:23:00
- admin 原创
- 26
问题描述:
我正在尝试使用 python 将字符串转换为单词列表。我想要采取类似以下的做法:
string = 'This is a string, with words!'
然后转换成这样的形式:
list = ['This', 'is', 'a', 'string', 'with', 'words']
注意省略了标点符号和空格。最快的解决方法是什么?
解决方案 1:
鉴于回复较晚,我认为这对其他偶然发现这篇文章的人来说是最简单的方法:
>>> string = 'This is a string, with words!'
>>> string.split()
['This', 'is', 'a', 'string,', 'with', 'words!']
解决方案 2:
尝试一下:
import re
mystr = 'This is a string, with words!'
wordList = re.sub("[^w]", " ", mystr).split()
工作原理:
来自文档:
re.sub(pattern, repl, string, count=0, flags=0)
返回通过用替换 repl 替换字符串中最左边不重叠的模式而获得的字符串。如果未找到模式,则返回不变的字符串。repl 可以是字符串或函数。
所以在我们的例子中:
模式是任何非字母数字字符。
[\w] 表示任意字母数字字符,相当于字符集 [a-zA-Z0-9_]
a 到 z、A 到 Z、0 到 9 和下划线。
因此我们匹配任何非字母数字字符并将其替换为空格。
然后我们使用 split() 方法,用空格分割字符串并将其转换为列表
所以‘你好世界’
变成‘hello world’
使用 re.sub
然后是 [‘hello’,‘world’]
在 split() 之后
如果有任何疑问,请告诉我。
解决方案 3:
要正确地做到这一点相当复杂。对于您的研究,它被称为单词标记化。如果您想看看其他人做了什么,您应该看看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'.']
解决方案 4:
最简单的方法:
>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'w+', string)
['This', 'is', 'a', 'string', 'with', 'words']
解决方案 5:
string.punctuation
为了完整性使用:
import re
import string
x = re.sub('['+string.punctuation+']', '', s).split()
这也处理换行符。
解决方案 6:
嗯,你可以使用
import re
list = re.sub(r'[.!,;?]', ' ', string).split()
请注意,和都是string
内置list
类型的名称,因此您可能不想将它们用作变量名。
解决方案 7:
受到@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']
解决方案 8:
我个人认为这比提供的答案稍微清晰一些
def split_to_words(sentence):
return list(filter(lambda w: len(w) > 0, re.split('W+', sentence))) #Use sentence.lower(), if needed
解决方案 9:
单词的正则表达式可以为您提供最大的控制权。您需要仔细考虑如何处理带有破折号或撇号的单词,例如“I'm”。
解决方案 10:
list=mystr.split(" ",mystr.count(" "))
解决方案 11:
这样,你就可以消除字母表之外的每个特殊字符:
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']
我不确定这是否快速或最佳,甚至是否是正确的编程方式。
解决方案 12:
def split_string(string):
return string.split()
此函数将返回给定字符串的单词列表。在这种情况下,如果我们按如下方式调用该函数,
string = 'This is a string, with words!'
split_string(string)
该函数的返回输出为
['This', 'is', 'a', 'string,', 'with', 'words!']
解决方案 13:
使用关键词法启动词典理解并填写相关部分。
您可以使用 .split() 方法获取字符串中的单词列表:https://www.w3schools.com/python/ref_string_split.asp
sentence = "What is the Airspeed Velocity of an Unladen Swallow?"
split_word = sentence.split()
words = {word for word in split_word}
print(words)
output - {'What', 'the', 'of', 'an', 'Unladen', 'Airspeed', 'Swallow?',
'Velocity', 'is'}
解决方案 14:
这是我在不能使用正则表达式的编码挑战中的尝试,
outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')
撇号的作用看起来很有趣。
解决方案 15:
可能不太优雅,但至少你知道发生了什么。
my_str = "Simple sample, test! is, olny".lower()
my_lst =[]
temp=""
len_my_str = len(my_str)
number_letter_in_data=0
list_words_number=0
for number_letter_in_data in range(0, len_my_str, 1):
if my_str[number_letter_in_data] in [',', '.', '!', '(', ')', ':', ';', '-']:
pass
else:
if my_str[number_letter_in_data] in [' ']:
#if you want longer than 3 char words
if len(temp)>3:
list_words_number +=1
my_lst.append(temp)
temp=""
else:
pass
else:
temp = temp+my_str[number_letter_in_data]
my_lst.append(temp)
print(my_lst)
解决方案 16:
string = '这是一个带有文字的字符串!'
列表 = [string.split() 中的单词]
打印(列表)
['这', '是', '一个', '字符串,', '带有', '单词!']
解决方案 17:
您可以尝试这样做:
tryTrans = string.maketrans(",!", " ")
str = "This is a string, with words!"
str = str.translate(tryTrans)
listOfWords = str.split()
- 2025年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)