如何在Python中将字符串列表连接成一个字符串 [英] How can I join a list of string into one string in Python

查看:209
本文介绍了如何在Python中将字符串列表连接成一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用.join()方法将字符串列表连接为一个字符串.但是,看起来结果仍然是相同的,其中输出仍然生成字母列表而不是单词.这是相关的代码:

I am trying to join a list of strings into one string using .join()method. However, it seems like the result is still the same where the output still producing a list of alphabet instead a word. Here's the relevent code:

import sys
import traceback
import weka.core.jvm as jvm
#import wekaexamples.helper as helper
from weka.core.converters import Loader
from weka.classifiers import Classifier


def main(args):
# load a dataset
 loader = Loader(classname="weka.core.converters.ArffLoader")
 train = loader.load_file("C:/Users/Syahirah/Desktop/Train_FYP.arff")
 train.class_index = train.num_attributes - 1
 test = loader.load_file("C:/Users/Syahirah/Desktop/Test_FYP_prediction.arff")
 test.class_is_last()

# classifier
 cls = Classifier(classname="weka.classifiers.bayes.NaiveBayes")
 cls.build_classifier(train)

# output predictions
#print("ID - actual - predicted ")
 for index, inst in enumerate(test):
    #print "\n", inst
    varinst = str(inst)
    #print type(varinst),varinst
    split_inst = varinst.split(',') 
    kata = split_inst[1]
    semua = ' '.join(kata)
    print semua

这是输出:

T h e
c u s t o m e r s
a r e
a l l o w e d
t o
r e s e r v e
r o o m
o n l i n e
'
b y
t h e
w a y
t h e y
a b l e
t o
c h a n g e
o r
c a n c e l
t h e i r
r e s e r v a t i o n

所需的输出应如下所示:

Desired output should be like this:

The customers are allowed to reserve room online, by the way they able to 
change or cancel their reservation

推荐答案

在.py文件的第一行中添加以下行:

Add this line at the first line of your .py file:

from __future__ import print_function

下一步,更改以下几行:

Next, change these lines:

semua = ' '.join(kata)
print semua

收件人:

semua = ''.join(kata)
print(semua, end='')

您要确保不在不需要的地方添加空格和换行符.

You want to make sure you're not adding spaces and newlines where not needed.

这篇关于如何在Python中将字符串列表连接成一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆