【问题标题】:Omitting of String Identifier ' ' in python在 python 中省略字符串标识符“”
【发布时间】:2017-07-19 13:15:32
【问题描述】:
def Interpretation_is(sentence):
    print(sentence.split())
    print(sentence.split()[0])

    there = 'distant place'
    he = 'gender identity'

    if 'place' in setence.split()[0]:
        print(sentence.replace('is','exists'))
    if 'identity' in sentence.split()[0]:
        print(sentence.replace('is','equal to'))

Interpretation_is('there is a woman')
Interpretation_is('he is a boy')

上面的代码专门针对“是”的含义改写给定的句子

由于只关心它的前一个词,主语,所以我只取了 sentence.split()[0] 并再次评估它的含义

问题是,如果我取 sentence.split()[0],我最终会得到 'there' 作为字符串,但我想再次让 python 将其读取为 由另一个元组或字符串集合组成的变量,例如there = 'distant place or location',并检查其中是否存在字符串'place or location'。

附加问题 1) 以一种高级的方式,我想组成一些属于所谓的 place 组的词组,例如 place = {there, here} 然后让程序检查 sentence.split()[0] 是否真的属于这个组。

我该怎么做?

附加问题 2) 当我引用一个词时,如 is = {exist, parity}。如果我按照数学符号记下它,则没有给出“顺序”,但是如果我将其作为列表或元组,例如 is = (exist, parity) 或 is = [exist, parity],则不可避免地会给出“顺序” .

python 中的哪个数据结构中不包含“顺序”?

我可以查看任何建议或参考资料吗?

【问题讨论】:

  • 您可能想研究使用 Python 的 dictionary 结构,但我并不完全清楚您想要的输出。
  • 我正在考虑对给定句子进行改写。 @ason​​gtoruin 希望你能看到我的回答

标签: python string list data-structures


【解决方案1】:
def Interpretation_is(sentence):
     print(sentence.split())
     print(sentence.split()[0])

     place = ('there', 'here')
     gender_identity = ('he', 'she')

     if sentence.split()[0] in place:
          print(sentence.replace('is','exists'))
     if sentence.split()[0] in gender_identity:
          print(sentence.replace('is','equal to'))

Interpretation_is('there is a woman')
Interpretation_is('he is a boy')

【讨论】:

    【解决方案2】:

    你得到'there'作为一个字符串,因为你将字符串(句子)分割成一个字符串列表。

    您正在寻找的是将字符串转换为变量,您可以在这里找到答案To convert string to variable name

    Q2:在这种情况下,您想使用第一个字符串作为键创建一个字典,并创建一个句子其余部分(字符串)的元组并将其用作值。

    string = 'there is a boy'
    l = string.split()
    d = {l[0]: tuple(l[1:])}
    

    【讨论】:

      猜你喜欢
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2013-05-30
      • 2020-12-14
      相关资源
      最近更新 更多