精华内容
下载资源
问答
  • python 出现SyntaxError: non-keyword arg after keyword arg错误解决办法 前言:  在Python中,这两个是python中的可变参数,*arg表示任意多个无名参数,类型为tuple,**kwargs表示关键字参数,为dict,使用时需将...
  • 关键字抓取器 通过抓取Google为之提供的... 运行它: node scraper.js --keyword="<keyword>" --limit=<limit> --file="<output>" 例如: node scraper.js --keyword="web scraping" --limit=50 --file="keywords.txt
  • LS-DYAN中文使用手册和KEYWORD USER'S MANUAL VOLUME I 2011年版
  • Key work scaper for making keywords
  • xingwa-baidu-keyword USAGE var httpClient = require("xingwa-baidu-keyword").httpClient // 获取网页内容 var stringData = httpClient.requestSync('http://www.eg.com', 3000, 'utf-8', function (err, res){ ...
  • 使用rf中条件判断常用关键字,比如根据某一个关键字运行结果判断下一步怎么走
  • DONUT: CTC-based Query-by-Example Keyword Spotting
  • 主要介绍了python的keyword模块用法,实例分析了Python中keyword模块的基本使用技巧,需要的朋友可以参考下
  • LS-DYNA_Keyword_Manual_971_Rev5-beta
  • 语言:English Amazon Keyword Harvester PRO和反向ASIN 智能反向ASIN查找和Amazon Long Tail Keyword Harvester ...免费! 从竞争对手那里收获关键词!
  • Public key encryption with keyword search
  • ISO 14230-1:1999 Road vehicles-Diagnostic systems-Keyword Protocol 2000-Part 1:Physical layer,ISO 14230-2:1999 Road vehicles-Diagnostic systems-Keyword Protocol 2000-Part 2:Data link layer,ISO ...
  • TF-IDF keyword extract

    2018-07-08 21:09:14
    TF-IDF keyword extract TF-IDF keyword extract TF-IDF keyword extract
  • Elasticsearch教程(19) 详解mapping之keyword

    千次阅读 2020-08-28 18:10:15
    详解mapping之keyword1 前言2 核心类型2.1 关键词:keyword2.1.1 适合用keyword的例子2.1.2 说明2.1.3 实验2.1.4 手动设置mapping2.1.5 ignore_above是什么? 1 前言 本文基于ES7.6,如果是之前版本,是有区别的。 ...

    1 前言

    • 本文基于ES7.6,如果是之前版本,是有区别的。
    • ES支持的字段类型很多,但工作中常用的也就那些核心字段。 一开始学习ES时,掌握好常用的类型,不必要精通每一种,如果工作中遇到了需要用到特殊类型再去研究。
    • 学习一门技术要先广度后深度,不能陷入”只见树木,不见森林“。

    2 核心类型

    2.1 关键词:keyword

    keyword类型通常存储结构性数据,而不是毫无规律可言的文本信息。

    2.1.1 适合用keyword的例子

    场景
    订单状态的枚举值1:未付款;2:已付款;3:申请退款;4:已退款
    HTTP状态码200;400;500;404
    手机号/邮箱/性别对手机号没必要分词,也不需要数学计算,所以也不能设为数字类型
    用户画像标签学生,IT男,屌丝女,孕妈,社会中产

    2.1.2 说明

    • ES把keyword类型的值当作词根存在倒排索引中,不进行分词。
    • keyword适合存结构化数据,比如name,age,性别,手机号,status(数据状态),tags(标签),HttpCode(404,200,500)等。
    • 字段常用来精确查询,过滤,排序,聚合时,应设为keyword,而不是数值型。
    • 如果某个字段你经常用来做range查询, 你还是设置为数值型(integer,long),ES对数字的range有优化。
    • 还可以把字段设为multi-field,这样又有keyword类型又有数值类型, 方便各个方式的使用。
    • 最长支持32766个UTF-8类型的字符,但放入倒排索引时,只截取前一段字符串,长度由ignore_above参数决定。

    2.1.3 实验

    (1)创建一个文档

    PUT /pigg_user/_doc/1
    {
      "name": "冬哥",
      "age": 32
    }
    

    (2)查询数据

    GET /pigg_user/_doc/1/_source
    
    #返回结果如下,说明插入成功:
    {
      "name" : "冬哥",
      "age" : 32
    }
    

    (3)查询name="冬哥"的数据

    GET /pigg_user/_search
    {
      "query": {
        "term": {
          "name": "冬哥"
        }
      }
    }
    
    #返回结果如下,居然没有搜索到???
    {
      ...省略其它信息...
      "hits" : {
        "total" : {
          "value" : 0,
          "relation" : "eq"
        },
        "max_score" : null,
        "hits" : [ ]
      }
    }
    

    (4)查看文档的mapping
    要想探知没有搜到的原因,得先看排查文档的mapping。
    发现name是text类型,其下面有一个keyword子类型。

    GET /pigg_user/_mapping
    
    #返回如下
    {
      "pigg_user" : {
        "mappings" : {
          "properties" : {
            "age" : {
              "type" : "long"
            },
            "name" : {
              "type" : "text",
              "fields" : {
                "keyword" : {          #这行的keyword是字段名,全称是name.keyword
                  "type" : "keyword",  #这行的keyword是指类型
                  "ignore_above" : 256 #这里的ignore_above下面会讲
                }
              }
            }
          }
        }
      }
    }
    

    (5)分析原因
    如果不设置mapping,ES默认把字符串设为text类型,并包含一个keyword子类型。
    name是text类型,“冬哥”这个词已经被拆成“冬”和“哥”这2个词项。
    所以上面用term来匹配“冬哥”时,查询不到数据。
    简单理解:

    • “name”这个字段按照“冬”和“哥”2个词存的,根据“冬”或者“哥”都能term查询到文档。
    • “name.keyword”这个字段存储的是“冬哥”这完整字符串。
    #根据name匹配“冬”,可以查询到文档
    GET /pigg_user/_search
    {
      "query": {
        "term": {
          "name": "冬"
        }
      }
    }
    
    #根据name.keyword匹配"冬哥",可以查询到文档
    GET /pigg_user/_search
    {
      "query": {
        "term": {
          "name.keyword": "冬哥"
        }
      }
    }
    
    #根据name.keyword匹配"冬",查询不到文档
    GET /pigg_user/_search
    {
      "query": {
        "term": {
          "name.keyword": "冬"
        }
      }
    }
    

    2.1.4 手动设置mapping

    #先删除之前创建的index
    DELETE pigg_user
    
    #设置name为keyword,age为short。
    PUT pigg_user
    {
      "mappings": {
        "properties": {
          "name": {
            "type":  "keyword"
          },
          "age": {
            "type": "short"
          }
        }
      }
    }
    
    #新增一个文档
    PUT /pigg_user/_doc/1
    {
      "name": "冬哥",
      "age": 32
    }
    
    #根据name精确匹配,可以查到数据
    GET /pigg_user/_search
    {
      "query": {
        "term": {
          "name": "冬哥"
        }
      }
    }
    

    2.1.5 ignore_above是什么?

    首先随意往ES插一条数据:

    put my_index/_doc/1
    {
      "name": "李星云"
    }
    

    查看ES自动生成的mapping,name是text类型,其下还有子类型keyword,且"ignore_above" : 256

    GET /my_index/_mapping
    
    name定义如下:
    "properties" : {
      "name" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      }
    }
    

    对于keyword类型, 可设置ignore_above限定字符长度。超过 ignore_above 的字符会被存储,但不会被倒排索引。比如ignore_above=4,”abc“,”abcd“,”abcde“都能存进ES,但是不能根据”abcde“检索到数据。

    【1】创建一个keyword类型的字段,ignore_above=4

    PUT test_index
    {
      "mappings": {
        "_doc": {
          "properties": {
            "message": {
              "type": "keyword",
              "ignore_above": 4
            }
          }
        }
      }
    }
    

    【2】向索引插入3条数据:

    PUT /test_index/_doc/1
    {
      "message": "abc"
    }
    
    PUT /test_index/_doc/2
    {
      "message": "abcd"
    }
    
    PUT /test_index/_doc/3
    {
      "message": "abcde"
    }
    

    此时ES倒排索引是:

    词项文档ID
    abc1
    abcd2

    【3】根据message进行terms聚合:

    GET /test_index/_search
    {
      "size": 0, 
      "aggs": {
        "term_message": {
          "terms": {
            "field": "message",
            "size": 10
          }
        }
      }
    }
    

    返回结果:

    {
      "took" : 2,
      "timed_out" : false,
      "_shards" : {
        "total" : 5,
        "successful" : 5,
        "skipped" : 0,
        "failed" : 0
      },
      "hits" : {
        "total" : 3,
        "max_score" : 1.0,
        "hits" : [
          {
            "_index" : "test_index",
            "_type" : "_doc",
            "_id" : "2",
            "_score" : 1.0,
            "_source" : {
              "message" : "abcd"
            }
          },
          {
            "_index" : "test_index",
            "_type" : "_doc",
            "_id" : "1",
            "_score" : 1.0,
            "_source" : {
              "message" : "abc"
            }
          },
          {
            "_index" : "test_index",
            "_type" : "_doc",
            "_id" : "3",
            "_score" : 1.0,
            "_source" : {
              "message" : "abcde"
            }
          }
        ]
      },
      "aggregations" : {
        "term_message" : {
          "doc_count_error_upper_bound" : 0,
          "sum_other_doc_count" : 0,
          "buckets" : [#注意这分组里没有”abcde“
            {
              "key" : "abc",
              "doc_count" : 1
            },
            {
              "key" : "abcd",
              "doc_count" : 1
            }
          ]
        }
      }
    }
    

    【4】根据”abcde“进行term精确查询,结果为空

    GET /test_index/_search
    {
      "query": {
        "term": {
          "message": "abcde"
        }
      }
    }
    
    然后结果:
      "hits" : {
        "total" : 0,
        "max_score" : null,
        "hits" : [ ]
      }
    

    通过上面结果能知道”abcde“已经存入ES,也可以搜索出来,但是不存在词项”abcde“,不能根据”abcde“作为词项进行检索。
    对于已存在的keyword字段,其ignore_above子属性可以修改,但只对新数据有效。

    展开全文
  • 成功解决TypeError: distplot() got an unexpected keyword argument 'y' 目录 解决问题 解决思路 解决方法 解决问题 TypeError: distplot() got an unexpected keyword argument 'y' 解决...

    成功解决TypeError: distplot() got an unexpected keyword argument 'y'

     

     

     

    目录

    解决问题

    解决思路

    解决方法


     

     

     

    解决问题

    TypeError: distplot() got an unexpected keyword argument 'y'

     

     

     

    解决思路

    类型错误:distplot()得到了一个意外的关键字参数'y'

     

     

     

    解决方法

    fg=sns.JointGrid(x=cols[0],y=cols[1],data=data_frame,)
    fg.plot_marginals(sns.distplot)

    distplot()函数中,只接受一个输入数据,即有x,没有y

    def distplot Found at: seaborn.distributions
    
    def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None, 
        hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, 
        color=None, vertical=False, norm_hist=False, axlabel=None, 
        label=None, ax=None, x=None):
        """DEPRECATED: Flexibly plot a univariate distribution of observations.
        
        .. warning::
        This function is deprecated and will be removed in a future version.
        Please adapt your code to use one of two new functions:
        
        - :func:`displot`, a figure-level function with a similar flexibility
        over the kind of plot to draw
        - :func:`histplot`, an axes-level function for plotting histograms,
        including with kernel density smoothing
        
        This function combines the matplotlib ``hist`` function (with automatic
        calculation of a good default bin size) with the seaborn :func:`kdeplot`
        and :func:`rugplot` functions. It can also fit ``scipy.stats``
        distributions and plot the estimated PDF over the data.
        
        Parameters
        ----------
        a : Series, 1d-array, or list.
        Observed data. If this is a Series object with a ``name`` attribute,
        the name will be used to label the data axis.
        bins : argument for matplotlib hist(), or None, optional
        Specification of hist bins. If unspecified, as reference rule is used
        that tries to find a useful default.
        hist : bool, optional
        Whether to plot a (normed) histogram.
        kde : bool, optional
        Whether to plot a gaussian kernel density estimate.
        rug : bool, optional
        Whether to draw a rugplot on the support axis.
        fit : random variable object, optional
        An object with `fit` method, returning a tuple that can be passed to a
        `pdf` method a positional arguments following a grid of values to
        evaluate the pdf on.
        hist_kws : dict, optional
        Keyword arguments for :meth:`matplotlib.axes.Axes.hist`.
        kde_kws : dict, optional
        Keyword arguments for :func:`kdeplot`.
        rug_kws : dict, optional
        Keyword arguments for :func:`rugplot`.
        color : matplotlib color, optional
        Color to plot everything but the fitted curve in.
        vertical : bool, optional
        If True, observed values are on y-axis.
        norm_hist : bool, optional
        If True, the histogram height shows a density rather than a count.
        This is implied if a KDE or fitted density is plotted.
        axlabel : string, False, or None, optional
        Name for the support axis label. If None, will try to get it
        from a.name if False, do not set a label.
        label : string, optional
        Legend label for the relevant component of the plot.
        ax : matplotlib axis, optional
        If provided, plot on this axis.
        
        Returns
        -------
        ax : matplotlib Axes
        Returns the Axes object with the plot for further tweaking.
        
        See Also
        --------
        kdeplot : Show a univariate or bivariate distribution with a kernel
        density estimate.
        rugplot : Draw small vertical lines to show each observation in a
        distribution.
        
        Examples
        --------
        
        Show a default plot with a kernel density estimate and histogram with bin
        size determined automatically with a reference rule:
        
        .. plot::
        :context: close-figs
        
        >>> import seaborn as sns, numpy as np
        >>> sns.set_theme(); np.random.seed(0)
        >>> x = np.random.randn(100)
        >>> ax = sns.distplot(x)
        
        Use Pandas objects to get an informative axis label:
        
        .. plot::
        :context: close-figs
        
        >>> import pandas as pd
        >>> x = pd.Series(x, name="x variable")
        >>> ax = sns.distplot(x)
        
        Plot the distribution with a kernel density estimate and rug plot:
        
        .. plot::
        :context: close-figs
        
        >>> ax = sns.distplot(x, rug=True, hist=False)
        
        Plot the distribution with a histogram and maximum likelihood gaussian
        distribution fit:
        
        .. plot::
        :context: close-figs
        
        >>> from scipy.stats import norm
        >>> ax = sns.distplot(x, fit=norm, kde=False)
        
        Plot the distribution on the vertical axis:
        
        .. plot::
        :context: close-figs
        
        >>> ax = sns.distplot(x, vertical=True)
        
        Change the color of all the plot elements:
        
        .. plot::
        :context: close-figs
        
        >>> sns.set_color_codes()
        >>> ax = sns.distplot(x, color="y")
        
        Pass specific parameters to the underlying plot functions:
        
        .. plot::
        :context: close-figs
        
        >>> ax = sns.distplot(x, rug=True, rug_kws={"color": "g"},
        ...                   kde_kws={"color": "k", "lw": 3, "label": "KDE"},
        ...                   hist_kws={"histtype": "step", "linewidth": 3,
        ...                             "alpha": 1, "color": "g"})
        
        """
        if kde and not hist:
            axes_level_suggestion = "`kdeplot` (an axes-level function for kernel 
             density plots)."
        else:
            axes_level_suggestion = "`histplot` (an axes-level function for 
             histograms)."
        msg = "`distplot` is a deprecated function and will be removed in a future 
         version. "\
        "Please adapt your code to use either `displot` (a figure-level function 
         with "\
        "similar flexibility) or " + axes_level_suggestion
        warnings.warn(msg, FutureWarning)
        if ax is None:
            ax = plt.gca()
        # Intelligently label the support axis
        label_ax = bool(axlabel)
        if axlabel is None and hasattr(a, "name"):
            axlabel = a.name
            if axlabel is not None:
                label_ax = True
        # Support new-style API
        if x is not None:
            a = x
        # Make a a 1-d float array
        a = np.asarray(a, float)
        if a.ndim > 1:
            a = a.squeeze()
        # Drop null values from array
        a = remove_na(a)
        # Decide if the hist is normed
        norm_hist = norm_hist or kde or fit is not None
        # Handle dictionary defaults
        hist_kws = {} if hist_kws is None else hist_kws.copy()
        kde_kws = {} if kde_kws is None else kde_kws.copy()
        rug_kws = {} if rug_kws is None else rug_kws.copy()
        fit_kws = {} if fit_kws is None else fit_kws.copy()
        # Get the color from the current color cycle
        if color is None:
            if vertical:
                line, = ax.plot(0, a.mean())
            else:
                line, = ax.plot(a.mean(), 0)
            color = line.get_color()
            line.remove()
        # Plug the label into the right kwarg dictionary
        if label is not None:
            if hist:
                hist_kws["label"] = label
            elif kde:
                kde_kws["label"] = label
            elif rug:
                rug_kws["label"] = label
            elif fit:
                fit_kws["label"] = label
        if hist:
            if bins is None:
                bins = min(_freedman_diaconis_bins(a), 50)
            hist_kws.setdefault("alpha", 0.4)
            hist_kws.setdefault("density", norm_hist)
            orientation = "horizontal" if vertical else "vertical"
            hist_color = hist_kws.pop("color", color)
            ax.hist(a, bins, orientation=orientation, color=hist_color, **hist_kws)
            if hist_color != color:
                hist_kws["color"] = hist_color
        if kde:
            kde_color = kde_kws.pop("color", color)
            kdeplot(a, vertical=vertical, ax=ax, color=kde_color, **kde_kws)
            if kde_color != color:
                kde_kws["color"] = kde_color
        if rug:
            rug_color = rug_kws.pop("color", color)
            axis = "y" if vertical else "x"
            rugplot(a, axis=axis, ax=ax, color=rug_color, **rug_kws)
            if rug_color != color:
                rug_kws["color"] = rug_color
        if fit is not None:
            def pdf(x):
                return fit.pdf(x, *params)
            
            fit_color = fit_kws.pop("color", "#282828")
            gridsize = fit_kws.pop("gridsize", 200)
            cut = fit_kws.pop("cut", 3)
            clip = fit_kws.pop("clip", (-np.inf, np.inf))
            bw = stats.gaussian_kde(a).scotts_factor() * a.std(ddof=1)
            x = _kde_support(a, bw, gridsize, cut, clip)
            params = fit.fit(a)
            y = pdf(x)
            if vertical:
                x, y = y, x
            ax.plot(x, y, color=fit_color, **fit_kws)
            if fit_color != "#282828":
                fit_kws["color"] = fit_color
        if label_ax:
            if vertical:
                ax.set_ylabel(axlabel)
            else:
                ax.set_xlabel(axlabel)
        return ax

     

     

     

     

     

     

     

    展开全文
  • 最新最全的ANSYS/LS-DYNA用户关键字手册,有了这东西,很多困难都可以解决了
  • # Error, keyword only arguments f(a=1) # Allowed, it's a keyword argument keyword argument that is required def f(*, a): pass f() # Error, argument required f(1) # Error, keyword only arguments f(a=1)...

            python函数具有各种灵活的参数, 功能着实强大. 不过因为过于灵活, 故比较难于理清, 所以给初学者带来了不小的困扰. 以下是我搜集的资料, 力图将这个问题明朗化.

    1. parameter 和 argument

            以前一直认为这两个单词的含义是相同的, 今天才发现其实不然.
            parameter 为函数定义时的叫法, 它指明了函数可以接受的argument类型. 可以理解为C语言中的形参;
            argument 为函数调用时的叫法, 可以理解为实参, 即传入的值;

    2. 我理解的 位置参数(positional) 和 关键字参数(keyword)

            从参考文档中可知, 函数定义时确定了五种参数, 但可以简化为两种基本类型, 其余的都可以在此基础上进行引申:

    基本类型:
            位置参数(positional):   传参时前面不带 "变量名=", 顺序不可变, 按顺序赋给相应的局部变量.
            关键字参数(keyword):  传参时前面加上 "变量名=", 顺序可变,    按名称赋给同名的局部变量.

    引申:
            仅位置参数(positional-only): 在 / 之前定义的参数, 传参时不带变量名. 这个在 python 3.8 中可以自己定义, 不过内置函数早已经使用这种方法了, 可参考 help() 输出的内部函数说明.
            位置或关键字参数(positional_or_keyword): 在 / 后面和 * 号前面定义的参数, 即我们自定义函数时最常用的. 传参时可以把它当作位置参数或关键字参数看待, 可以带变量名也可以不带. 这就是我们自定义的函数与内置函数的区别之处了, 这一点最迷惑人.
            集合位置参数(var_positional): 即函数定义时采用 *args 指定的参数. 我们一般都把它理解为"可变参数", 实际上理解为"集合位置参数"最精确. 传参时不能带变量名. 注意: 根据"关键字参数不能在位置参数前面"的原则, *args 会将之前的参数全部转化为 位置参数, 之后的参数全部转化为 关键字参数
            仅关键字参数(keyword-only): 在 * 后面定义的参数(或在 *args 后面定义, ... 类似于 *args). 传参时必需带变量名.
            集合关键字参数(var_keyword): 即函数定义时采用 **args 指定的参数. 它可以接受我们传入的任意个数的关键字参数. 传参时必须带变量名.

            注意: 传递参数时, "关键字参数不能在位置参数前面", 否则就会报错. 根据这条原则, 那么上述顺序也应该是 parameter 定义的顺序了.

            另外根据定义时是否有默认参数, 又可分为两种修饰类型, 它们不影响参数的基本类型定义:
            必需参数: 定义时没有默认值的参数, 调用时不可省略.
            可选参数: 定义时有默认值的参数,     调用时可省略.

            举一个例子, 这个是 python 3.8 里面的例子:

    def func(a, b=2, /, c, d=4, *, e=5, f): 
        pass

             a, b 是 仅位置参数; a 是必需的, b 则是可选的;
            c, d 是 位置或关键字参数;
            e, f 是 仅关键字参数;

             而我们平常所自定义的简单函数

    def f(a): pass

            应该等价于

    def f(/, a, *): pass

    3. 参考资料

            下面的文档一部分是我从 python 3.7.4 的手册摘录来, 另一部分是网上找到的相关资料, 大家可以参考着看一下.

    3.1 parameter

            A named entity in a function(or method) definition that specifies an argument (or in some cases, arguments) that the function can accept. There are five kinds of parameter:

            positional-or-keyword: specifies an argument that can be passed either positionally or as a keyword argument. This is the default kind of parameter, for example foo and bar in the following:
    def func(foo, bar=None):
        pass

            positional-only: specifies an argument that can be supplied only by position. Python has no syntax for defining positional-only parameters. However, some built-in functions have positional-only parameters (e.g. abs()).

            keyword-only: specifies an argument that can be supplied only by keyword. Keyword-only parameters can be defined by including a single var-positional parameter or bare * in the parameter list of the function definition before them, for example kw_only1 and kw_only2 in the following:
    def func(arg, *, kw_only1, kw_only2):
        pass

            var-positional: specifies that an arbitrary sequence of positional arguments can be provided (in addition to any positional arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with *, for example args in the following:
    def func(*args, **kwargs):
        pass

            var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with **, for example kwargs in the example above.

            Parameters can specify both optional and required arguments, as well as default values for some optional arguments.

            See also the argument glossary entry, the FAQ question on the difference between arguments and parameters, the inspect.Parameter class, the Function definitions section, and PEP 362.

    3.2 argument

            A value passed to a function (or method) when calling the function. There are two kinds of argument:

            keyword argument: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. For example, 3 and 5 are both keyword arguments in the following calls to complex():
    complex(real=3, imag=5)
    complex(**{'real': 3, 'imag': 5})

            positional argument: an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and/or be passed as elements of an iterable preceded by *. For example, 3 and 5 are both positional arguments in the following calls:
    complex(3, 5)
    complex(*(3, 5))

             Arguments are assigned to the named local variables in a function body. See the Calls section for the rules governing this assignment. Syntactically, any expression can be used to represent an argument; the evaluated value is assigned to the local variable.
              See also the parameter glossary entry, the FAQ question on the difference between arguments and parameters, and PEP 362.

    3.3 What is the difference between arguments and parameters?

            Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
    def func(foo, bar=None, **kwargs):
        pass

            foo, bar and kwargs are parameters of func. However, when calling func, for example:
    func(42, bar=314, extra=somevar)
            the values 42, 314, and somevar are arguments.


    3.4 What does the slash(/) in the parameter list of a function mean?

             A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, pow() is a function that accepts positional-only parameters. Its documentation looks like this:
    >>> help(pow)
    Help on built-in function pow in module builtins:
    pow(x, y, z=None, /)
              Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
              Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form.

              The slash at the end of the parameter list means that all three parameters are positional-only. Thus, calling pow() with keyword aguments would lead to an error:
    >>> pow(x=3, y=4)
    Traceback (most recent call last):
        File "", line 1, in
    TypeError: pow() takes no keyword arguments

              Note that as of this writing this is only documentational and no valid syntax in Python, although there is PEP 570, which proposes a syntax for position-only parameters in Python.

    3.5 https://stackoverflow.com/questions/9450656/positional-argument-v-s-keyword-argument

            Since python 3.8 introduced positional arguments only, this post need an update.
            Positional arguments, keyword arguments, required arguments and optional arguments are often confused. Positional arguments ARE NOT THE SAME AS required arguments. and keywords arguments ARE NOT THE SAME AS optional arguments.
            Positional arguments are arguments that can be called by their position in the function definition.
            Keyword arguments are arguments that can be called by their name.
            Required arguments are arguments that must passed to the function.
            Optional arguments are argument that can be not passed to the function. In python optional arguments are arguments that have a default value.

    Positional argument that is optional (python 3.8)
    def f(a=2, /): pass
    f()         # Allowed, argument is optional
    f(1)        # Allowed, it's a positional argument
    f(a=1)      # Error, positional only argument


    Positional argument that is required (python 3.8)
    def f(a, /): pass
    f()         # Error, argument required
    f(1)        # Allowed, it's a positional argument
    f(a=1)      # Error, positional only argument


    Keyword argument that is optional
    def f(*, a=1): pass
    f()         # Allowed
    f(1)        # Error, keyword only arguments
    f(a=1)      # Allowed, it's a keyword argument


    keyword argument that is required
    def f(*, a): pass
    f()         # Error, argument required
    f(1)        # Error, keyword only arguments
    f(a=1)      # Allowed, it's a keyword argument


    Positional and keyword argument that is optional
    def f(a=1): pass
    f()         # Allowed, argument is optional
    f(1)        # Allowed, it's a positional argument
    f(a=1)      # Allowed, it's a keyword argument
        # In fact this function is the same as
    def f(/, a=1, *): pass


    Positional and keyword argument that is required
    def f(a): pass
    f()         # Error, argument required
    f(1)        # Allowed, it's a positional argument
    f(a=1)      # Allowed, it's a keyword argument
        # In fact this function is the same as
    def f(/, a, *): pass


            Conclusion, an argument can be optional or required not both at the same time. It can also be positional, keyword or both at the same time.

            Python 3.8 introduced positional only parameters.
    def f(positional_argument, /, positional_or_keyword_argument, *, keyword_argument):
        pass


    3.6 https://docs.python.org/3.8/whatsnew/3.8.html#positional-only-parameters

    Positional-only parameters
            There is a new function parameter syntax / to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments. This is the same notation shown by help() for C functions annotated with Larry Hastings' Argument Clinic tool.
            In the following example, parameters a and b are positional-only, while c or d can be positional or keyword, and e or f are required to be keywords:
    def f(a, b, /, c, d, *, e, f):
            print(a, b, c, d, e, f)

            The following is a valid call:
    f(10, 20, 30, d=40, e=50, f=60)

            However, these are invalid calls:
    f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword argument
    f(10, 20, 30, 40, 50, f=60)                   # e must be a keyword argument


            One use case for this notation is that it allows pure Python functions to fully emulate behaviors of existing C coded functions. For example, the built-in divmod() function does not accept keyword arguments:
    def divmod(a, b, /):
            "Emulate the built in divmod() function"
            return (a // b, a % b)

            Another use case is to preclude keyword arguments when the parameter name is not helpful. For example, the builtin len() function has the signature len(obj, /). This precludes awkward calls such as:
    len(obj='hello')  # The "obj" keyword argument impairs readability


            A further benefit of marking a parameter as positional-only is that it allows the parameter name to be changed in the future without risk of breaking client code. For example, in the statistics module, the parameter name dist may be changed in the future. This was made possible with the following function specification:
    def quantiles(dist, /, *, n=4, method='exclusive')
            ...


            Since the parameters to the left of / are not exposed as possible keywords, the parameters names remain available for use in **kwargs:
    >>> def f(a, b, /, **kwargs):
    ...   print(a, b, kwargs)
    ...
    >>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
    10 20 {'a': 1, 'b': 2, 'c': 3}
            This greatly simplifies the implementation of functions and methods that need to accept arbitrary keyword arguments. For example, here is an excerpt from code in the collections module:

    class Counter(dict):
            def __init__(self, iterable=None, /, **kwds):
                    # Note "iterable" is a possible keyword argument
    See PEP 570 for a full description.
    (Contributed by Pablo Galindo in bpo-36540.)

    3.7 Python 中的关键字(具名)参数: 如何使用它们

    https://blog.csdn.net/u012040909/article/details/80170573

    展开全文
  • python got an unexpected keyword argument

    千次阅读 2021-06-07 21:49:59
    模拟了一下异常: def add(x,y): return x+y print(add(bbb=3)) 报错: TypeError: add() got an unexpected keyword argument 'bbb' 原因: add函数没有参数bbb,传了一个未知参数bbb 解决方法: def add(x,y,*args...

     

    模拟了一下异常:

     

    def add(x,y):
       return x+y
    
    print(add(bbb=3))

    报错:

    TypeError: add() got an unexpected keyword argument 'bbb'
     

    原因:

    add函数没有参数bbb,传了一个未知参数bbb

     

    解决方法:

    def add(x,y,*args,**kwargs):
       return x+y
    
    print(add(bbb=3))

    这样也不报错

    def add(**kwargs):
       return 4
    
    print(add(pre=4,bbb=3))

     

    展开全文
  • 成功解决TypeError: __init__() got an unexpected keyword argument 'serialized_options' 目录 解决问题 解决思路 解决方法 解决问题 TypeError: __init__() got an unexpected keyword argument '...
  • 但位置实参必须放在关键字实参的前面 foo(y=2,1) SyntaxError: positional argument follows keyword argument foo(1,y=2) 可以混用,但不能对一个形参重复赋值 foo(1,y=2,x=3) #报错 三:默认参数:在函数定义...
  • ES内置分词器之keyword/pattern详细解析
  • ElasticSearch设置字段的keyword属性

    千次阅读 2021-04-12 11:35:05
    这个时候,我们就需要对该字段设置一个keyword属性,并将该keyword属性的type设置为keyword。这样,我们在查询或者在聚合时候,通过该属性下的keyword字段,可以实现完全匹配。 示例: 对一个nested对象下的name...
  • Elasticsearch number和keyword滥用

    万次阅读 2019-02-26 16:36:22
    之前有社区上反映ES 2.x -...总结,在ES5.x里,一定要注意数值类型是否需要做范围查询,看似数值,但其实只用于Term或者Terms这类精确匹配的,应该定义为keyword类型。在ES6.x里已经不用再关注该问题,它会自动转换。
  • 程序 import requests if __name__=='__main__': url='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword' ...TypeError: request() got an unexpected keyword argument 'date'
  • es中keyword与不加keyword区别

    千次阅读 2020-02-29 23:04:05
    https://segmentfault.com/q/1010000017312707
  • Organic Keyword: What Is an Organic Keyword?

    千次阅读 2019-04-09 11:46:01
    Organic Keyword: What Is an Organic Keyword? An organic keyword is a keyword used to attract free traffic through search engine optimization (SEO). Organic keywords contrast with pay-per-click (PPC) ...
  • ES查询中.keyword详解

    万次阅读 2020-01-13 00:20:48
    ES5.0及以后的版本取消了string类型,将原先的string类型拆分为text和keyword两种类型。它们的区别在于text会对字段进行分词处理而keyword则不会。 当你没有以IndexTemplate等形式为你的索引字段预先指定mapping的话...
  • If you need to index structured content such as email addresses, hostnames, status codes, or tags, it is likely that you should rather use a keyword field. Keyword datatype A field to index ...
  • 文章目录一、概述二、使用 ...上边介绍的text文本字段在映射时要设置分词器,keyword字段为关键字字段,通常搜索keyword是按照整体搜索,所以创建keyword字段的索引时是不进行分词的,比如:邮政...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 241,987
精华内容 96,794
关键字:

keyword