Psychopy TextStim неправильно отображает пробелы в многострочной строке, которую я пытаюсь использовать.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Psychopy TextStim неправильно отображает пробелы в многострочной строке, которую я пытаюсь использовать.

Сообщение Anonymous »

Я пытаюсь отобразить три строки текста как часть стимула с помощью Psychopy. Первая и третья строки содержат случайно сгенерированные слова (из словаря общих слов), а средняя строка содержит триграмму, положение которой меняется в зависимости от целочисленного значения, переданного в функцию. Каждая строка содержит ровно 15 символов, а средняя строка включает триграмму, окруженную пробелами (ее положение варьируется). Когда я печатаю строку на терминале, она всегда отображается правильно, но не тогда, когда она назначена TextStim.
Внизу я включил модифицированную версию, которая окружает триграмму словами и одним пространство между ними работает. Однако я надеюсь понять, почему эта первая версия не работает. Я просто не могу понять, что вызывает ошибку (изображения того, как ошибка влияет на дисплей, приведены ниже)
from psychopy import visual, event
import random
import csv
from numpy.random import multinomial

# creating the dictionary from a file
def word_dict(file):
wordlist = []
input_file = open(file)
reader = csv.reader(input_file, delimiter = ',')
next(reader)
for row in reader:
for word in row:
wordlist.append(word)
input_file.close()

words = {len(word) : [] for word in wordlist}
for word in wordlist:
words[len(word)].append(word)

return words

test_dict = word_dict("wordlist.csv")

# this function generates text stimuli for the top and bottom rows in the string.
# first determines how many words and then randomly selects words of appropriate length
def random_string(words: dict):
n = random.randint(2,4)
if n == 2:
while True:
numbers = multinomial(14, [1/2.] * 2) # determines word length
if 0 not in numbers:
break
string = (f"{random.choice(words[numbers[0]])} "
f"{random.choice(words[numbers[1]])}")
elif n == 3:
while True:
numbers = multinomial(13, [1/3.] * 3)
if 0 not in numbers:
break
string = (f"{random.choice(words[numbers[0]])} "
f"{random.choice(words[numbers[1]])} "
f"{random.choice(words[numbers[2]])}")
elif n == 4:
while True:
numbers = multinomial(12, [1/4.] * 4)
if 0 not in numbers:
break
string = (f"{random.choice(words[numbers[0]])} "
f"{random.choice(words[numbers[1]])} "
f"{random.choice(words[numbers[2]])} "
f"{random.choice(words[numbers[3]])}")

return string

# The string that is assigned to the textStim is generated with the following function
def generate_stimuli(pos, type):
if type == "cue":
stimulus = "###"
elif type == "target":
# Generate random letters for the middle row
letter1 = chr(random.randint(ord('a'), ord('z')))
letter2 = chr(random.randint(ord('a'), ord('z')))
letter3 = chr(random.randint(ord('a'), ord('z')))
stimulus = letter1 + letter2 + letter3

# set the position for the middle row
right_side = 13 - pos
left_side = 12 - right_side
center_string = (left_side * " ") + stimulus + (right_side * " ")

# create random strings for above and below the target
above = random_string(test_dict) # text_dict is dictionary of common words
below = random_string(test_dict) # text_dict is dictionary of common words
if type == "cue":
return center_string
elif type == "target":
return (above + '\n' + center_string + '\n' + below)

# If I call the above function and then print the result it works correctly.
# The only problem is when I pass it to the text object in visual.TextStim

win = visual.Window(
fullscr=True,
size=[1920, 1080],
screen=0,
color=[+1] * 3,
units="deg"
)

target_string = visual.TextStim(
win=win,
anchorHoriz="center",
anchorVert="center",
font="courier new",
color=[-1] * 3,
units="deg",
height=1.2
)

stimulus = generate_stimuli(1, "target")
target_string.text = stimulus

target_string.draw()
win.flip()
event.waitKeys()

win.close()

По сути, я должен передать строку из трех строк длиной ровно 15 символов в TextStim, но средняя строка продолжает отображаться неправильно.
Если я замените center_string = (left_side * " ") + стимул + (right_side * " ") на center_string = (left_side * "*") + стимул + (right_side * "*") он отображается правильно. но если я вернусь к пустым местам, этого не произойдет снова.
используя "*" с позицией == 1
Используя " " с позицией == 1Я просто не могу понять, почему пустые места отображаются неправильно. Может ли якорьHoriz центрировать каждую строку независимо, а некоторые пробелы не переносятся? Изучив код классов, я до сих пор не могу понять.
Измененная версия ниже работает нормально, но я все еще пытаюсь понять, почему приведенное выше не работает
def random_word(length: int, words: dict):
word_length = length - 1
return random.choice(words[word_length])

def generate_stimuli(pos, type):
if type == "cue":
stimulus = "###"
elif type == "target":
# Generate random letters for the trigram
letter1 = chr(random.randint(ord('a'), ord('z')))
letter2 = chr(random.randint(ord('a'), ord('z')))
letter3 = chr(random.randint(ord('a'), ord('z')))
stimulus = letter1 + letter2 + letter3

# set the position for the stimuli
right_side = 13 - pos
left_side = 12 - right_side

# select words for the right and left sides
if right_side > 1:
word_right = random_word(right_side, test_dict)
else:
word_right = " "

if left_side > 1:
word_left = random_word(left_side, test_dict)
else:
word_left = ""

if type == "cue":
center_string = (left_side * " ") + stimulus + (right_side * " ")
elif type == "target":
if pos == 1:
center_string = f"{stimulus} {word_right}"
elif pos == 14:
center_string = f"{word_left} {stimulus}"
else:
center_string = f"{word_left} {stimulus} {word_right}"

# create random strings for above and below the trigram
above = random_string(test_dict)
below = random_string(test_dict)

if type == "cue":
return center_string
elif type == "target":
return (above + '\n' + center_string + '\n' + below)



Подробнее здесь: https://stackoverflow.com/questions/789 ... ultiline-s
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»