Python拆分单词,但字母返回

2024-10-01 17:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将此文本拆分为单词,但split()始终返回字母而不是整个单词。在

f="""Police have seized fake money being used to buy goods in ALAWA. An 
investigation is underway to locate where it came from. It's understood 50 
dollar notes with Chinese symbols have emerged at a Woolworths, butcher 
and bottle shop."""
words = set(line.strip() for line in f)
print(words)

这是我收到的输出:

^{pr2}$

你知道为什么吗?在


Tags: toin文本have字母line单词fake
3条回答

words = set(line.strip() for line in f)

你认为你可能在看线,但实际上你是在一根巨大的绳子上循环。在Python中,您可以迭代一个字符串,它将返回一个包含组成该字符串的所有字符的列表。在

另外,strip函数只删除字符串https://docs.python.org/2/library/stdtypes.html?highlight=strip#str.strip开头和结尾的某些字符。在您的例子中,由于省略了任何参数,它将简单地删除所有前导和尾随空格。在

您可以使用split函数https://docs.python.org/2/library/stdtypes.html?highlight=split#str.split和一个空格作为参数来实现您想要的结果。在

只需写下:

words = set(f.split()) #you have used strip instead of split

line.strip()将逐个横切每个字符。方法strip()返回字符串的一个副本,其中所有字符都已从字符串的开始和结尾剥离。您应该使用split(),它将字符串按空格分隔成字符串列表。在

相关问题 更多 >

    热门问题