【问题标题】:How can I join a list of string into one string in Pythonpython - 如何在Python中将字符串列表加入一个字符串
【发布时间】:2017-11-20 15:58:02
【问题描述】:

我正在尝试使用.join()method 将字符串列表加入一个字符串。然而,看起来结果仍然是相同的,输出仍然产生一个字母列表而不是一个单词。以下是相关代码:

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

想要的输出应该是这样的:

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

【问题讨论】:

  • 您的test 变量包含什么?这没什么好继续的。
  • @Coldspeed 实例变量
  • test 变量包含一个对象列表及其变量。在这段代码中,我提取了第二个变量word。从单词列表中,我想把它做成一个完整的句子形式。我真的很抱歉我的解释。它没有很好地解释,因为我对python真的很陌生。

标签: python string python-2.7 join


【解决方案1】:

在 .py 文件的第一行添加这一行:

from __future__ import print_function

接下来,更改这些行:

semua = ' '.join(kata)
print semua

收件人:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2011-05-25
    • 2014-04-26
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多