【问题标题】:Stuck in a while loop in python卡在python中的while循环中
【发布时间】:2017-12-06 21:53:19
【问题描述】:

我对 python 很陌生,所以请耐心等待。我有这段代码,我在下面插入了一个 while 循环,以确保每次给定名称时它都会检查以验证名称是否在 csv 中,然后如果不是,它会给出错误并要求一个新名称。我的问题是我似乎无法摆脱困境。即使有一个我知道的新名称在 csv 中,它仍然停留在循环中。我的问题是如何让这段代码循环运行并验证名称是否存在?任何帮助都会很棒。如果有更好的编写方法,我什至愿意更改整个代码。

这是我得到的:

import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

这是我输入时的结果: 供参考。 Steve Miller 不在 csv 文件中,因此第一个响应是正确的。但是,Sri Mantri 在文件中,它应该继续打印出她名下的所有列表。

Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system

这是代码运行时的输出结果。

Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours

csv 看起来像这样:

First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4

【问题讨论】:

  • 带有第二个inputwhile-loop 位于for-loop 内,因此它只查看当前处理的row
  • 那么你认为我应该删除 for 循环吗?
  • @stevenmiller 您的 csv 文件没有任何逗号。
  • @Goyo,我不太确定如何将 csv 添加到问题中,所以我只是从 python 中提取了它。

标签: python loops csv while-loop


【解决方案1】:

您在 while 循环中要求输入,该循环从不检查除当前行之外的任何行。看起来您正在尝试遍历整个列表以查看名称是否在其中的任何位置(这在性能方面很粗糙,但我不会因为进入那个 xD 而让您感到困惑)所以您的输入检查和循环需要是有点像这样移动:

import csv

with open('Report1.csv') as csvfile:
  hour_summation = {}
  read_csv = csv.reader(csvfile, delimiter=',')
  name_found = False
  while not name_found:
    # take user input for name
    full_name = input('Enter your full name: ').lower()
    # start search at top of file. Have to do this or each loop will
    # start at the end of the file after the first check.
    csvfile.seek(0)
    for row in read_csv:
      # check to see if row matches name
      if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
        name_found = True
        hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))

    # name wasn't found, so repeat process
    if not name_found:
      # name wasn't found, go back to start of while loop
      print('Name is not in system')
    else:
      # break out of while loop. Technically not required since while
      # will exit here anyway, but clarity is nice
      break

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

【讨论】:

  • 这真的很接近我的需要,但是它只打印出与用户名关联的 csv 的第一行。我正在尝试从该名称获取完整的小时报告。
  • @stevenmiller 是的,我搞砸了。我刚刚删除了一条不应该存在的线。我有一个额外的休息时间过早地打破了 for 循环。检查编辑并重试。应该让您使用该名称的每一行。
  • 你太棒了,伙计!这正是我一直在寻找的。现在,只要我能确保可以避免拼写错误的名字就好了。大声笑
【解决方案2】:

假设文件可以包含与给定全名相关的多行,请尝试以下操作:

import csv

full_name = input('Enter your full name: ').lower()
run=1
while run:    
    with open('Report1.csv') as csvfile:
        hour_summation = {}
        read_csv = csv.reader(csvfile, delimiter=',')
        for row in read_csv:
            if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))

    if hour_summation:
        print('This is {} full hours report:'.format(full_name))
        for k, v in hour_summation.items():
            print(k + ': ' + str(v) + ' hours')
        run=0
    else:
        print('Name is not in system')
        full_name = input('Enter your full name: ').lower() # following your code, 
                                                            # request for a new full name comes only in case no results for the 1st one 

【讨论】:

  • 这很好用,除了循环只对一个错误有用。因此,当我连续输入两个不在 csv 中的名称时,它只工作 1 次然后停止。
  • 我已经添加了上层循环,所以它会询问名称直到它得到一个有效的名称,然后它会停止。逻辑和代码可以根据需求不同
【解决方案3】:
import csv

full_name = input('Enter your full name: ').lower()
bucle = True
with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    while bucle:    
        for row in read_csv:
            if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
                bucle = False
        if bucle:
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
            csvfile.seek(0)

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
print(k + ': ' + str(v) + ' hours')

【讨论】:

  • 如果不将文件返回到顶部,这将无法工作。 csv.reader 不会返回列表或可以反复重复的内容。
  • 它现在可以工作,但只有 1x 通过循环然后出错。
  • 他在寻找错误的东西。你必须寻找文件,而不是我的答案所做的读者。
  • 好吧,我的错。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多