替换列表中的字符串

时间:2019-08-01 10:19:51

标签: python replace

这是我之前的question的后续工作,我正尝试将一个列表中的字符串替换为另一列表中的字符串。

The "file" argument must be of type string. Received type undefined
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-app@0.1.0 deploy: `gh-pages -d build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the my-app@0.1.0 deploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

预期输出:

@RequestMapping(value = "/{param:^((?!txt$|xml$).)*$}", method = RequestMethod.GET)
public String showPage(@PathVariable(value = "param") String pageParam, Model model, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException
{
    return pageParam;
}

如果import numpy as np from difflib import SequenceMatcher from pprint import pprint def similar(a, to_match): percent_similarity = [SequenceMatcher(None, a, b).ratio() for b in to_match] max_value_index = [i for i, j in enumerate(percent_similarity) if j == max(percent_similarity)][0] map = [to_match[max_value_index] if max(percent_similarity) > 0.9 else a][0] return map if __name__ == '__main__': strlist = ['D-saturn 6-pluto', np.nan, 'D-astroid 3-cyclone', 'DL-astroid 3-cyclone', 'DL-astroid', 'D-comment', 'literal'] to_match = ['saturn 6-pluto', 'pluto', 'astroid 3-cyclone', 'D-comment', 'D-astroid'] for item in strlist: map = [similar(item, to_match) for item in strlist] pprint(map) 中没有['saturn 6-pluto', np.nan, 'astroid 3-cyclone', 'astroid 3-cyclone', 'D-astroid', 'D-comment', 'literal'] ,则该代码有效。 我想检查字符串是否为np.nan,如果存在则返回strlist。 但是,我不确定如何在列表理解nan

中使用nan语句

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

编辑:

那么,如果类型不是字符串,则如何更改similar函数以返回项本身呢?

def similar(a, to_match):
    if type(a) is not str:
        return a
    percent_similarity = [SequenceMatcher(None, a, b).ratio() for b in to_match]
    max_value_index = [i for i, j in enumerate(percent_similarity) if j == max(percent_similarity)][0]
    ret = [to_match[max_value_index] if max(percent_similarity) > 0.9 else a][0]
    return ret

您可以先过滤strlist,然后再在for循环中通过以下方式进行过滤

strlist = [s for s in strlist if type(s) is str]

答案 1 :(得分:0)

您可以在另一个map函数中编写if

map = [similar(item, to_match) if isinstance(item, str) else item for item in strlist]