如何将Python代码输出的多行单词拼接为空格分隔单句?
解决方案
方案一:先收集单词再拼接输出(推荐)
这种方式先把所有符合条件的单词存入列表,最后用空格拼接成单句一次性输出,性能更优,尤其适合处理大量单词的场景:
with open("wordslist.txt") as f: words_list = {word.removesuffix("\n") for word in f} target_words = [] with open("neg.csv") as g: for tweete in g: for word in tweete.split(): if word not in words_list: target_words.append(word) # 用空格拼接所有单词并打印 print(' '.join(target_words))
方案二:修改print的结束符
直接修改print函数的end参数,将默认的换行符\n替换为空格,这样每个单词输出后会用空格分隔:
with open("wordslist.txt") as f: words_list = {word.removesuffix("\n") for word in f} with open("neg.csv") as g: for tweete in g: for word in tweete.split(): if word not in words_list: # 替换换行符为空格 print(word, end=' ') # 最后打印一个换行,让输出格式更规范 print()
注意:方案二的输出末尾会多一个空格,如果对格式要求严格,推荐使用方案一。
内容的提问来源于stack exchange,提问作者Zulfi A
相关产品推荐
相关产品推荐

