Python DataFrame проблема цикла и среза - PullRequest
0 голосов
/ 03 мая 2018
import random
import re
import pandas as pd
df1 = pd.DataFrame({"Greetings": ["Greetings to you too", "hi", "hello", "hey", "greetings", "sup", "what's up", "yo"]})
df2 = pd.DataFrame({"Farewell": ["GoodBye", "see you", "bye", "laters"]})

frames = [df1, df2]
df3=pd.concat(frames, axis=1, join='outer', copy=True)
def check_for_greet():
 while True:
    try:
        sentence = input("Start chatting:  ")
        wordList = re.sub("[^\w]", " ",  sentence).split()
        if sentence == "$$$":
                return "END"

        for word in wordList:
            for col in df3.columns:
                if word.lower() in df3[col].values:
                    print (df3[col][0])
                    break

Вышеописанное прекрасно работает теперь между столбцами (спасибо @ R.yan), однако проблема возникает только тогда, когда я набираю "привет привет", он печатает дважды:

Start chatting:  hi hi
Greetings to you too
Greetings to you too

Почему это происходит, я прерываю цикл for, продолжая возвращаться к циклу while?!

1 Ответ

0 голосов
/ 03 мая 2018

Замените вашу функцию следующим:

def check_for_greet():
 while True:
    try:
        sentence = input("Start chatting:  ")
        wordList = re.sub("[^\w]", " ",  sentence).split()
        if sentence == "$$$":
                return "END"

        for col in df3.columns:
            if sentence.lower() in df3[col].values:
                print df3[col][0]
        continue

Выход:

Start chatting:  hi
Greetings to you too
Start chatting:  bye
GoodBye

ответ для вашего дублированного вывода

word_found = False
for word in wordList:          
    for col in df3.columns:
        if word.lower() in df3[col].values:
            print (df3[col][0])
            word_found = True
    if word_found:
        break
...