#python #python-3.x #python-2.7
Вопрос:
Может кто-нибудь, пожалуйста, помочь мне с этим ? Я попытался добавить глобальный в thirdword_dp , но это не работает в первый раз, когда я использовал только третье слово, но у меня была та же ошибка Для первого usr_choice, эта программа будет искать в ячейках только из B, и если выбран второй usr_choice, программа должна искать два слова в B и одно слово в C.
Я получаю : > печать(«это:» thirdword_dp) UnboundLocalError: локальная переменная «thirdword_dp», на которую ссылались перед назначением
def finds_word_3():
usr_choice = input('Would you like to search just in NAME or DP?n Your choice: ')
if usr_choice == '':
print('Nothing Selected')
elif usr_choice.lower() == 'name':
# find first word
for cell in range(1, 2000):
data = sheet.cell(row=cell, column=2).value
if data is not None:
data = data.lower()
data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
big_data1.append(data_no_pct)
x1 = " ".join(big_data1)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(20)
print(most_occur1)
for word, cnt in most_occur1:
answer = input('Is ' word.upper() ' a relevant word for you?n Y or N: ')
if answer.upper() == 'Y':
firstword = word
break
else:
print('No word selected')
print('this is: ' firstword)
# find 2nd word
for cell in range(1, 2000):
data = sheet.cell(row=cell, column=2).value
if data is not None:
data = data.lower()
if firstword in data:
data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
big_data2.append(data_no_pct)
x1 = " ".join(big_data2)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(20)
print(most_occur1)
for word, cnt in most_occur1:
if word != firstword:
answer = input('Is ' word.upper() ' a relevant word for you?n Y or N: ')
if answer.upper() == 'Y':
secondword = word
break
else:
print('No word selected')
print('this is: ' secondword)
# find 3rd word
for cell in range(1, 2000):
data = sheet.cell(row=cell, column=2).value
if data is not None:
data = data.lower()
if firstword in data:
if secondword in data:
data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
big_data3.append(data_no_pct)
x1 = " ".join(big_data3)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(20)
print(most_occur1)
for word, cnt in most_occur1:
if word != firstword:
if word != secondword:
answer = input('Is ' word.upper() ' a relevant word for you?n Y or N: ')
if answer.upper() == 'Y':
thirdword = word
break
else:
print('No word selected')
print('this is: ' thirdword)
print(
'{ANDnAttributesContain[item_name:' firstword ']nAttributesContain[item_name:' secondword ']nAttributesContain[item_name:' thirdword ']n}')
elif usr_choice.lower() == 'dp':
# find first word
for cell in range(1, 2000):
data = sheet.cell(row=cell, column=2).value
if data is not None:
data = data.lower()
data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
big_data1.append(data_no_pct)
x1 = " ".join(big_data1)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(20)
print(most_occur1)
for word, cnt in most_occur1:
answer = input('Is ' word.upper() ' a relevant word for you?n Y or N: ')
if answer.upper() == 'Y':
firstword = word
break
else:
print('No word selected')
print('this is: ' firstword)
# find 2nd word
for cell in range(1, 2000):
data = sheet.cell(row=cell, column=2).value
if data is not None:
data = data.lower()
if firstword in data:
data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
big_data2.append(data_no_pct)
x1 = " ".join(big_data2)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(20)
print(most_occur1)
for word, cnt in most_occur1:
if word != firstword:
answer = input('Is ' word.upper() ' a relevant word for you?n Y or N: ')
if answer.upper() == 'Y':
secondword = word
break
else:
print('No word selected')
print('this is: ' secondword)
# find 3rd word
for cell in range(1, 2000):
data_dp = sheet.cell(row=cell, column=3).value
if data_dp is not None:
if data is not None:
data_dp = data_dp.lower()
if firstword in data:
if secondword in data:
data_no_pct = data_dp.translate(str.maketrans('', '', string.punctuation))
big_data3.append(data_no_pct)
x1 = " ".join(big_data3)
split_it1 = x1.split()
Count1 = Counter(split_it1)
most_occur1 = Count1.most_common(20)
print(most_occur1)
for word, cnt in most_occur1:
if word != firstword:
if word != secondword:
answer = input('Is ' word.upper() ' a relevant word for you?n Y or N: ')
if answer.upper() == 'Y':
thirdword_dp = word
break
else:
print('No word selected')
print('this is: ' thirdword_dp)
print(
'{ANDnAttributesContain[item_name:' firstword ']nAttributesContain[item_name:' secondword ']nAttributesContain[bullet_point:' thirdword_dp ']n}')
else:
print('no go')
Сообщение об ошибке, которое я получаю, выглядит так:
Traceback (most recent call last):
File "C:/Users/ancoman/PycharmProjects/pythonProject2/main.py", line 244, in <module> choice()
File "C:/Users/ancoman/PycharmProjects/pythonProject2/main.py", line 23, in choice finds_word_3()
File "C:/Users/ancoman/PycharmProjects/pythonProject2/main.py", line 229, in finds_word_3 dp()
File "C:/Users/ancoman/PycharmProjects/pythonProject2/main.py", line 216,
in dp print('this is: ' thirdword_dp)
UnboundLocalError: local variable 'thirdword_dp' referenced before assignment
Комментарии:
1. Пожалуйста, опубликуйте все сообщение об ошибке, начиная с обратной связи и заканчивая кодом в вашем вопросе.
2. Обратная связь (последний последний вызов): Файл «C:/Users/ancoman/PycharmProjects/pythonProject2/main.py», строка 244, в файле выбора <модуля> () «C:/Users/ancoman/PycharmProjects/pythonProject2/main.py», строка 23, в выборе файла finds_word_3 () «C:/Users/ancoman/PycharmProjects/pythonProject2/main.py», строка 229, в файле finds_word_3 dp () «C:/Users/ancoman/PycharmProjects/pythonProject2/main.py», строка 216, в dp print («это:» thirdword_dp) UnboundLocalError: локальная переменная «thirdword_dp», на которую ссылались перед назначением
3. Посмотрите на свой код, начинающийся со строки
for word, cnt in most_occur1:
. thirdword_dp определяется только в рамках третьего цикла ifif answer.upper() == 'Y': thirdword_dp = word
, если вы не уверены, что пытаетесь сделать, но, поскольку вы ссылаетесь на переменную вне этого цикла, она не определена.4. Спасибо. Моя цель — найти наиболее распространенное слово из ячеек в столбце C, но ищите это общее слово только в том случае, если ячейка из столбца B содержит переменные-первое и второе слово . Программа работает нормально, пока ей не придется печатать thirdword_dp
5. Можете ли вы предоставить образец ваших данных, в частности, о содержании
sheet.cell(row=cell, column=2).value0
. Мне не нужны все данные, просто образец, или, если данные являются конфиденциальными, предоставьте тестовые данные аналогичной формы.