【问题标题】:Iterating through a list of words to check if any start with a given string in Python遍历单词列表以检查是否有任何以 Python 中的给定字符串开头
【发布时间】:2017-05-10 13:29:06
【问题描述】:

我最近开始学习 Python,到目前为止,一切似乎都相当直观。

我有一个包含多行数据的文本文件。我正在遍历每一行,将其拆分为单词,现在我想遍历给定行上的每个单词以检查它是否以给定字符串开头,然后如果是,则将单词更改为其他内容。

到目前为止我有:

with open('test_inputfile.txt','r') as f:
for line in f:
    words = line.split('","')
    for word in words:
        if word.startswith('spam'):
            # change given word

但这不起作用,因为我似乎无法访问word.startswith() 函数。

我相信它一定很容易做到,因为到目前为止其他一切都非常简单!

谢谢。

【问题讨论】:

  • 您可能有一个空的可迭代对象,因为您应该拆分 ',' 而不是 '","'
  • @MosesKoledoye 不是空的,而是只有一个元素:整个line
  • @MosesKoledoye 文本文件的单词之间有逗号和双撇号
  • 您可能有类似"spam","second","third" 这样的行,在这种情况下,使用","(引号和逗号)作为分隔符将在第一个、中间和最后一个元素之间产生不同的行为。如果您将引号作为文本的一部分,只需使用逗号作为分隔符并在您的 startswith 方法中查找 "spam 而不是 spam
  • 能否请您发布您的输入文件的一部分?

标签: python string list loops


【解决方案1】:

你可以试试这个:

f = open('test_inputfile.txt').readlines()
f = [i.strip('\n').split(',') for i in f]
for line in f:
    for word in line:
       if word.startswith('spam'):

现在,f 存储了一个列表列表,其中包含每行中的所有单词。

【讨论】:

    【解决方案2】:

    如果您使用的是 CSV 数据,这可能会很有用。如果是这种情况,请将您的拆分更改为line.split(',')。否则请参见下文。

    使用startswith 函数时,实际上不需要拆分行,因为您只对行的开头感兴趣。有关startswith 函数的更多信息,请参阅here

    with open('test_inputfile.txt', 'r') as f: for line in f: if line.startswith('spam', 0, 4): # take action

    这有效地检查单词“垃圾邮件”是否在位置 0 到 4

    一切顺利:)

    【讨论】:

    • 也许我不清楚,我想检查每个 WORD 是否以“垃圾邮件”开头,而不是每一行。感谢您的帮助!
    【解决方案3】:

    您可能忘记去掉每行中的首尾双引号。但我强烈推荐使用csv 模块来处理csv数据:

    import csv
    with open('test_inputfile.txt','r') as f: 
      reader = csv.reader(f, delimiter=',', quotechar='"') 
      # both params are the default values anyway 
      for row in reader:
        for word in row:
          if word.startswith('spam'):
            # do stuff
    

    【讨论】:

    • 感谢您的回答,但是,我遇到了与原始代码相同的问题:我无法使用 word 的 .startswith() 函数
    【解决方案4】:

    你有一个这样的文件:

    "toast","eggs","bacon" 
    "orangejuice","spamandtoast","bagels"
    

    读取文件:

    with open("test_inputfile.txt", "r") as fs:
        for lines in fs:
            line = lines.split(",")
            for word in line:
                word = word.replace('"','') # removes the quotes
                if word.startswith("spam"):
                    print word
    

    您也可以在开头创建一个空列表wordlist = [],并添加列表中的每个单词。

    wordlist.append(word)

    最好使用csv 模块。

    【讨论】:

    • 这与我的代码基本相同,但我不能使用 'words.startswith()'。
    • 请张贴一点您输入的文字。
    • 看起来是这样的:"toast","eggs","bacon" "orangejuice","spamandtoast","bagels"(这里orangejuice换行)我想找到spamandtoast,然后比如改成yoghurt
    猜你喜欢
    • 2013-03-09
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多