将单个句子拆分为列表

时间:2015-09-25 03:20:33

标签: python

我在询问如何制作个人名单。不是如何找到标记为重复的子字符串。

我有以下文件

'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

我正在尝试将每个句子转换为一个列表,以便当我搜索单词“Gentlemen”时,它应该打印出整个句子。 我能够分割线,但我无法将它们转换为单独的列表。我从互联网上尝试过一些东西但到目前为止没有任何帮助。

这是什么

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

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:1)

Python字符串有split()方法:

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

编辑:正如@ShadowRanger在下面提到的那样,在没有参数的情况下运行split()会处理前导,尾随和连续的空格。