将单个句子拆分为lis

2024-04-28 20:47:29 发布

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

我问的是如何列出个人清单。不知道如何找到标记为duplicated for的子字符串。你知道吗

我有以下文件

'Gentlemen do not read each others mail.' Henry Stinson
'The more corrupt the state, the more numerous the laws.' Tacitus
'The price of freedom is eternal vigilance.' Thomas Jefferson
'Few false ideas have more firmly gripped the minds of so many intelligent men than the one that, if they just tried, they could invent a cipher that no one could break.' David Kahn
'Who will watch the watchmen.' Juvenal
'Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.' John Von Neumann
'They that give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.' Benjamin Franklin
'And so it often happens that an apparently ingenious idea is in fact a weakness which the scientific cryptographer seizes on for his solution.' Herbert Yardley

我试着把每个句子转换成一个列表,这样当我搜索单词say“绅士”时,它就会把整个句子打印出来。 我可以得到行分裂,但我无法将它们转换为个人名单。我从网上试过一些东西,但到目前为止没有任何帮助。你知道吗

这是什么

def myFun(filename):
    file = open(filename, "r")
    c1 = [ line for line in file ]
    for i in c1:
        print(i)

Tags: oftheinforsothatismore
2条回答

Python字符串有一个split()方法:

individual_words = 'This is my sentence.'.split()
print(len(individual_words)) # 4

编辑:正如@ShadowRanger在下面提到的,不带参数运行split()将处理前导、尾随和连续空格。你知道吗

可以使用in搜索字符串或数组,例如7 in a_list"I" in "where am I"

如果需要,可以直接在文件上迭代

 for line in open("my_file.txt")

尽管为了确保关闭,人们还是建议使用上下文管理器

 with open("my_file.txt") as f:
      for line in f:

这至少能让你走上正确的方向

如果您想搜索不区分大小写的,您可以简单地使用str.lower()

term.lower() in search_string.lower() #case insensitive

相关问题 更多 >