【问题标题】:Remove `\n` from a list [duplicate]从列表中删除 `\n` [重复]
【发布时间】:2017-09-04 05:43:17
【问题描述】:

我有一个列表,其中包含从在线网站上抓取的数据。列表是这样的

list1 = ['\nJob Description\n\nDESCRIPTION: Interacts with users and technical team members to analyze requirements and develop
technical design specifications.  Troubleshoot complex issues and make recommendations to improve efficiency and accurac
y. Interpret complex data, analyze results using statistical techniques and provide ongoing reports. Identify, analyze,
and interpret trends or patterns in complex data sets. Filter and "clean data, review reports, and performance indicator
s to locate and correct code problems. Work closely with management to prioritize business and information needs. Locate
 and define new process improvement opportunities. Employ excellent interpersonal and verbal communication skills necess
ary to effectively coordinate interrelated activities with coworkers, end-users, and management. Works autonomously with
 minimal supervision. Provides technical guidance and mentoring to other team members. Multi tasks and balances multiple
 assignments and priorities. Provides timely status updates.\nQUALIFICATIONS: Proven 5 years working experience as a dat
a analyst Technical expertise regarding data models, database design development, data mining and segmentation technique
s Knowledge of and experience with reporting packages (preferably Microsoft BI Stack), databases (SQL, DB2 etc.), and qu
ery language (SQL) Knowledge of statistics and experience using statistical packages for analyzing large datasets Strong
 analytical skills with the ability to collect, organize, analyze, and disseminate significant amounts of information wi
th attention to detail and accuracy Adept at queries, report writing and presenting findings\nNTT DATA is a leading IT s.............]

如何删除“\n”

请记住,在抓取时必须在循环中完成,以便抓取数据,“\n”并删除不需要的空格并将数据推送到 csv 中。

【问题讨论】:

  • 如果你有notepad++,你可以查找和替换
  • 需要在Python中完成
  • 我很确定 python 有一个 replace() 方法。如果是这样,它将类似于 list.replaceAll("\\n", "");
  • @Serge - 我也为此添加了原件。如果您希望我添加更多内容,请告诉我。

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

从单个字符串中删除 \n 相当简单。

line = '\nJob Description\n\nDESCRIPTION:'
line.replace('\n', ' ')

您对“不需要的空格”的构成不是很具体,但简单的假设是这意味着连续两个空格,一个简单的方法是.replace(' ', ' ') 删除双倍空格。将两者链接在一起,您最终会得到:

line.replace('\n', ' ').replace('  ', ' ')

这既简单又快速。但是,它不会删除所有多余的空格。例如,3 或 4 个空格的序列将变为 2 个空格。相反,您可以使用splitjoin 的组合来删除所有多余的空格。

' '.join(line.split())`

这会在所有空格处拆分字符串(包括换行符、制表符和其他空格)并使用单个空格重新连接它们。如果它不能满足您的需求,可以使用正则表达式,但正则表达式解析效率不高,但功能更强大。

import re
re.sub('\s{2,}', ' ', line)

这会将 2 个或多个空格替换为一个空格。

无论您使用哪种方法来清理单个字符串,您仍然需要将其应用于列表中的每个元素。如果你选择的方法比较复杂,你应该把它变成一个方法:

def process(line):
    return line.replace('\n', ' ').replace('  ',  ' ')

一种天真的方法是使用处理的每个元素重新构建列表。例如使用列表生成器:

processed_results = [process(line) for line in list]

对于一个非常大的列表,这可能是非常低效的。最好的方法是使用一次只处理一个元素而不重建整个列表的生成器。

generated_results = (process(line) for line in list1)

注意它看起来几乎与字符串理解方法相同。您可以像使用列表一样遍历它:

for result in generated_results:
    # do something

请记住,生成器在使用时会被消耗,因此如果您需要多次迭代结果,则可能需要改用列表。生成器可以通过以下方式转换为列表:

processed_results = list(generated_results)

TL;DR

最简单最有效的方法是使用splitjoin 删除多余的空格,并使用生成器来提高效率以避免重建整个列表:

generated_results = (' '.join(line.split) for line in list1)

【讨论】:

    【解决方案2】:

    试试这个:

    list2 = [x.replace('\n', '') for x in list1]
    

    它使用列表解析来遍历list1,并从原始成员中创建一个新列表,并在每个项目上调用str.replace,以用空字符串替换\n

    更多关于 python 列表推导 here.

    要删除空格,请将上面的代码更改为

    list2 = [x.replace('\n', '').replace(' ', '') for x in list1]
    

    【讨论】:

    • How to Answer 中所述,请避免回答不清楚、宽泛、SW 推荐、错字、基于意见、不可复制或重复的问题。写我的代码请求和省力的家庭作业问题对于Stack Overflow 来说是题外话,更适合专业的编码/辅导服务。好的问题坚持How to Ask,包括minimal reproducible example,有研究工作,并且有可能对未来的访问者有用。回答不恰当的问题会使网站更难导航并鼓励进一步提出此类问题,从而损害网站,这可能会赶走其他自愿提供时间和专业知识的用户。
    • @TigerhawkT3 仅仅因为问题不理想而否决答案是糟糕的形式。答案确实有助于回答问题。否决问题而不是答案。
    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多