問題:文字列内の単語を使用してリスト内のアイテムを特定し、アイテムを識別したりインデックスを返します。文字列内の単語を使用してリスト内のアイテムを特定し、アイテムを特定する
こんにちは、このサイトと他のサイトを検索して、問題の解決策を探しています。私が見つけた解決策は、リストは、文字列内のアイテムを持っているかどうかを判断することに成功している、
例:
any(word in str1 for word in List)
しかし、これはtrueまたはfalseを返し、およびコマンドで、
print word
私はリスト項目を探し、いずれかの項目を印刷したり、リスト内のインデックスを与えることができるソリューションを必要とエラー
を返します。
私はこれをAIとして使用していますが、これは数学の方程式を実行する能力があります。このためには、標準の "+、 - 、*、/"だけでなく単語の形式でもある演算子を見つける必要があります。たとえば、「プラス、マイナスなど」は、見つかった場合、プログラムは文字列内の項目をeval()が処理できる適切な標準演算子で置き換えることができます。プロジェクトから再適用
サンプルコード:
from __future__ import division
import re
from math import *
Listopp = ["+","-", "*","/"]
Listadd = ["add","plus"]
Listsub = ["subtract","minus"]
Listmult = ["times","multiply","x"]
Listdivide = [ "divide","over"]
Listmath =Listopp + Listadd + Listsub + Listmult + Listdivide
try:
str1 = raw_input("what is your math problem?")
if (any(word in str1 for word in Listmath) and re.findall(r"[-+]?\d*\.\d+|\d+",str1) != []):
# here is where the solution need to be placed
opp = Listmath.index(any(word in str1))
# needs to be identified or indexed
#Replaced with standard operators
if (opp in Listdivide):
str1 = str1.replace(opp ,"/")
if (opp in Listmult):
str1 = str1.replace(opp ,"*")
if (opp in Listsub):
str1 = str1.replace(opp ,"-")
if (opp in Listadd):
str1 = str1.replace(opp ,"+")
if (opp in Listopp):
pass
math = eval(str1)
if not float(math).is_integer():
print "rounded"
result = round(math, 3)
else:
print "real"
result = math
print result
else:
print "No suitable math problems found."
except Exception as e:
print e
このコード上の任意のヘルプやアドバイスをいただければ幸いです。
私はあなたが「間違っている」と確信しています。あなたが記述しているのは式パーサーであり、検索と置換よりもはるかに複雑です。例えば。 pyparsingを使用します:https://pyparsing.wikispaces.com/file/view/fourFn.py – thebjorn