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),但问题是当我输入" hi hi'时,它打印两次:
Start chatting: hi hi
Greetings to you too
Greetings to you too
为什么这样做,我打破for循环继续返回while循环?!
答案 0 :(得分:2)
用以下内容替换您的功能:
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