【问题标题】:Using the split() or find() function in python在 python 中使用 split() 或 find() 函数
【发布时间】:2016-02-21 18:20:50
【问题描述】:

我正在编写一个打开文件并查找如下行的程序:

X-DSPAM-Confidence:    0.8475. 

我想使用 split 和 find 函数来提取这些行并将其放入变量中。这是我写的代码:

fname = raw_input("Enter file name: ")
if len(fname) == 0:
    fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"): continue

拜托,拜托,我现在开始使用 python,所以请给我一些我能理解的简单的东西,以便以后帮助我。请,请。

【问题讨论】:

  • 为什么不直接if line = X-DSPAM-Confidence: 0.8475.
  • @Arman 我怀疑每次的值都是一样的
  • @wilbur ,那么为什么 not 在 if ?没有not,我认为这是真的
  • 对于已经发布的答案,我只能添加:人们,在处理文件时尝试每隔一段时间使用异常处理......哈哈

标签: python string find


【解决方案1】:

我认为唯一错误的部分是 not in if :

fname = raw_input("Enter file name: ")
if len(fname) == 0:
    fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"): 
        lines.append(line)

【讨论】:

    【解决方案2】:

    首先用raw_input()接收输入

    fname = raw_input("Enter file name: ")
    

    然后检查输入字符串是否为空:

    if not fname:
        fname = 'mbox-short.txt'
    

    然后,打开文件并逐行读取:

    lines = []
    with open(fname, 'r') as f:
        for line in f.readlines():
            if line.startswith("X-DSPAM-Confidence:"):
                lines.append(line)
    

    with open() as file 语句只是确保文件对象在您不再需要时关闭。 (退出with子句时会自动调用file.close()

    【讨论】:

      【解决方案3】:

      我知道这个是从哪里来的,因为我前段时间自己做过。据我记得你需要计算平均值:)

      fname = raw_input("Enter file name: ")
      fh = open(fname)
      count = 0
      sum = 0
      for line in fh:
          if not line.startswith("X-DSPAM-Confidence:") : continue
          count = count + 1
          pos = line.find(' ')
          sum = sum + float(line[pos:])
      average = sum/count
      

      【讨论】:

        【解决方案4】:

        你已经很接近了,你只需要在继续添加行下面添加一个语句到list

        fname = raw_input("Enter file name: ")
        if len(fname) == 0:
            fname = 'mbox-short.txt'
        fh = open(fname,'r')
        total = 0
        lines = []
        for line in fh:
            if not line.startswith("X-DSPAM-Confidence:"):
                continue
            lines.append(line) # will only execute if the continue is not executed
        fh.close()
        

        您还应该查看用于打开文件的with 关键字——它更安全、更容易。你会这样使用它(我还交换了你的 if 的逻辑 - 为你节省了一行和不必要的继续):

        fname = raw_input("Enter file name: ")
        if len(fname) == 0:
            fname = 'mbox-short.txt'
        total = 0
        good_lines = []
        with open(fname,'r') as fh:
            for line in fh:
                if line.startswith("X-DSPAM-Confidence:"):
                    good_lines.append(line)
        

        如果您只想要这些值,您可以使用 good_lines 列表进行列表理解,如下所示:

        values = [ l.split()[1] for l in good_lines ]
        

        【讨论】: